context-menu.tsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import { createRoot } from 'react-dom/client'
  2. import {
  3. StateField,
  4. StateEffect,
  5. Prec,
  6. EditorSelection,
  7. } from '@codemirror/state'
  8. import { EditorView, showTooltip, Tooltip, keymap } from '@codemirror/view'
  9. import { Word, Mark, getMarkAtPosition } from './spellchecker'
  10. import { debugConsole } from '@/utils/debugging'
  11. import {
  12. getSpellChecker,
  13. getSpellCheckLanguage,
  14. } from '@/features/source-editor/extensions/spelling/index'
  15. import { sendMB } from '@/infrastructure/event-tracking'
  16. import { SpellingSuggestions } from '@/features/source-editor/extensions/spelling/spelling-suggestions'
  17. import { SplitTestProvider } from '@/shared/context/split-test-context'
  18. import { addLearnedWord } from '@/features/source-editor/extensions/spelling/learned-words'
  19. import { postJSON } from '@/infrastructure/fetch-json'
  20. import { closeAllContextMenusEffect } from '../../utils/close-all-context-menus-effect'
  21. /*
  22. * The time until which a click event will be ignored, so it doesn't immediately close the spelling menu.
  23. * Safari emits an additional "click" event when event.preventDefault() is called in the "contextmenu" event listener.
  24. */
  25. let openingUntil = 0
  26. /*
  27. * Hide the spelling menu on click
  28. */
  29. const handleClickEvent = (event: MouseEvent, view: EditorView) => {
  30. if (Date.now() < openingUntil) {
  31. return
  32. }
  33. if (view.state.field(spellingMenuField, false)) {
  34. view.dispatch({
  35. effects: hideSpellingMenu.of(null),
  36. })
  37. }
  38. }
  39. /*
  40. * Detect when the user right-clicks on a misspelled word,
  41. * and show a menu of suggestions
  42. */
  43. const handleContextMenuEvent = (event: MouseEvent, view: EditorView) => {
  44. const position = view.posAtCoords(
  45. {
  46. x: event.pageX,
  47. y: event.pageY,
  48. },
  49. false
  50. )
  51. const targetMark = getMarkAtPosition(view, position)
  52. if (!targetMark) {
  53. return
  54. }
  55. const { value } = targetMark
  56. const targetWord = value.spec.word
  57. if (!targetWord) {
  58. debugConsole.debug(
  59. '>> spelling no word associated with decorated range, stopping'
  60. )
  61. return
  62. }
  63. event.preventDefault()
  64. openingUntil = Date.now() + 100
  65. view.dispatch({
  66. effects: [
  67. closeAllContextMenusEffect.of(null),
  68. showSpellingMenu.of({
  69. mark: targetMark,
  70. word: targetWord,
  71. }),
  72. ],
  73. })
  74. }
  75. const handleShortcutEvent = (view: EditorView) => {
  76. const targetMark = getMarkAtPosition(view, view.state.selection.main.from)
  77. if (!targetMark || !targetMark.value) {
  78. return false
  79. }
  80. view.dispatch({
  81. effects: [
  82. closeAllContextMenusEffect.of(null),
  83. showSpellingMenu.of({
  84. mark: targetMark,
  85. word: targetMark.value.spec.word,
  86. }),
  87. ],
  88. })
  89. return true
  90. }
  91. /*
  92. * Spelling menu "tooltip" field.
  93. * Manages the menu of suggestions shown on right-click
  94. */
  95. export const spellingMenuField = StateField.define<Tooltip | null>({
  96. create() {
  97. return null
  98. },
  99. update(value, transaction) {
  100. if (value) {
  101. value = {
  102. ...value,
  103. pos: transaction.changes.mapPos(value.pos),
  104. end: value.end ? transaction.changes.mapPos(value.end) : undefined,
  105. }
  106. }
  107. for (const effect of transaction.effects) {
  108. if (effect.is(hideSpellingMenu)) {
  109. value = null
  110. } else if (effect.is(showSpellingMenu)) {
  111. const { mark, word } = effect.value
  112. // Build a "Tooltip" showing the suggestions
  113. value = {
  114. pos: mark.from,
  115. end: mark.to,
  116. above: false,
  117. strictSide: false,
  118. create: createSpellingSuggestionList(word),
  119. }
  120. } else if (effect.is(closeAllContextMenusEffect)) {
  121. value = null
  122. }
  123. }
  124. return value
  125. },
  126. provide: field => {
  127. return [
  128. showTooltip.from(field),
  129. EditorView.domEventHandlers({
  130. contextmenu: handleContextMenuEvent,
  131. click: handleClickEvent,
  132. }),
  133. Prec.highest(
  134. keymap.of([
  135. { key: 'Ctrl-Space', run: handleShortcutEvent },
  136. { key: 'Alt-Space', run: handleShortcutEvent },
  137. ])
  138. ),
  139. ]
  140. },
  141. })
  142. const showSpellingMenu = StateEffect.define<{ mark: Mark; word: Word }>()
  143. export const hideSpellingMenu = StateEffect.define()
  144. /*
  145. * Creates the suggestion menu dom, to be displayed in the
  146. * spelling menu "tooltip"
  147. * */
  148. const createSpellingSuggestionList = (word: Word) => (view: EditorView) => {
  149. const dom = document.createElement('div')
  150. dom.classList.add('ol-cm-spelling-context-menu-tooltip')
  151. const root = createRoot(dom)
  152. root.render(
  153. <SplitTestProvider>
  154. <SpellingSuggestions
  155. word={word}
  156. spellCheckLanguage={getSpellCheckLanguage(view.state)}
  157. spellChecker={getSpellChecker(view.state)}
  158. handleClose={(focus = true) => {
  159. view.dispatch({
  160. effects: hideSpellingMenu.of(null),
  161. })
  162. if (focus) {
  163. view.focus()
  164. }
  165. }}
  166. handleLearnWord={() => {
  167. const tooltip = view.state.field(spellingMenuField)
  168. if (tooltip) {
  169. window.setTimeout(() => {
  170. view.dispatch({
  171. selection: EditorSelection.cursor(tooltip.end ?? tooltip.pos),
  172. })
  173. })
  174. }
  175. view.focus()
  176. postJSON('/spelling/learn', {
  177. body: {
  178. word: word.text,
  179. },
  180. })
  181. .then(() => {
  182. view.dispatch(addLearnedWord(word.text), {
  183. effects: hideSpellingMenu.of(null),
  184. })
  185. sendMB('spelling-word-added', {
  186. language: getSpellCheckLanguage(view.state),
  187. })
  188. })
  189. .catch(error => {
  190. debugConsole.error(error)
  191. })
  192. }}
  193. handleCorrectWord={(text: string) => {
  194. const tooltip = view.state.field(spellingMenuField)
  195. if (!tooltip) {
  196. throw new Error('No active tooltip')
  197. }
  198. const existingText = view.state.doc.sliceString(
  199. tooltip.pos,
  200. tooltip.end
  201. )
  202. if (existingText !== word.text) {
  203. return
  204. }
  205. window.setTimeout(() => {
  206. const changes = view.state.changes([
  207. { from: tooltip.pos, to: tooltip.end, insert: text },
  208. ])
  209. view.dispatch({
  210. changes,
  211. effects: [hideSpellingMenu.of(null)],
  212. selection: EditorSelection.cursor(tooltip.end ?? tooltip.pos).map(
  213. changes
  214. ),
  215. })
  216. })
  217. view.focus()
  218. sendMB('spelling-suggestion-click', {
  219. language: getSpellCheckLanguage(view.state),
  220. })
  221. }}
  222. />
  223. </SplitTestProvider>
  224. )
  225. const destroy = () => {
  226. root.unmount()
  227. }
  228. return { dom, destroy }
  229. }