use-codemirror-scope.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import { useCallback, useEffect, useRef } from 'react'
  2. import { EditorState } from '@codemirror/state'
  3. import useScopeValue from '../../../shared/hooks/use-scope-value'
  4. import useScopeEventEmitter from '../../../shared/hooks/use-scope-event-emitter'
  5. import useEventListener from '../../../shared/hooks/use-event-listener'
  6. import useScopeEventListener from '../../../shared/hooks/use-scope-event-listener'
  7. import { createExtensions } from '../extensions'
  8. import {
  9. lineHeights,
  10. setEditorTheme,
  11. setOptionsTheme,
  12. } from '../extensions/theme'
  13. import {
  14. restoreCursorPosition,
  15. setCursorLineAndScroll,
  16. setCursorPositionAndScroll,
  17. } from '../extensions/cursor-position'
  18. import {
  19. setAnnotations,
  20. showCompileLogDiagnostics,
  21. } from '../extensions/annotations'
  22. import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
  23. import { setCursorHighlights } from '../extensions/cursor-highlights'
  24. import {
  25. setLanguage,
  26. setMetadata,
  27. setSyntaxValidation,
  28. } from '../extensions/language'
  29. import { useIdeContext } from '../../../shared/context/ide-context'
  30. import { restoreScrollPosition } from '../extensions/scroll-position'
  31. import { setEditable } from '../extensions/editable'
  32. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  33. import { setAutoPair } from '../extensions/auto-pair'
  34. import { setAutoComplete } from '../extensions/auto-complete'
  35. import { usePhrases } from './use-phrases'
  36. import { setPhrases } from '../extensions/phrases'
  37. import {
  38. addLearnedWord,
  39. removeLearnedWord,
  40. resetLearnedWords,
  41. setSpelling,
  42. } from '../extensions/spelling'
  43. import {
  44. createChangeManager,
  45. dispatchEditorEvent,
  46. } from '../extensions/changes/change-manager'
  47. import { setKeybindings } from '../extensions/keybindings'
  48. import { Highlight } from '../../../../../types/highlight'
  49. import { EditorView } from '@codemirror/view'
  50. import { CurrentDoc } from '../../../../../types/current-doc'
  51. import { useErrorHandler } from 'react-error-boundary'
  52. import { setVisual } from '../extensions/visual/visual'
  53. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  54. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  55. import { setDocName } from '@/features/source-editor/extensions/doc-name'
  56. import isValidTexFile from '@/main/is-valid-tex-file'
  57. import { captureException } from '@/infrastructure/error-reporter'
  58. import grammarlyExtensionPresent from '@/shared/utils/grammarly'
  59. function useCodeMirrorScope(view: EditorView) {
  60. const ide = useIdeContext()
  61. const { fileTreeData } = useFileTreeData()
  62. const [permissions] = useScopeValue<{ write: boolean }>('permissions')
  63. // set up scope listeners
  64. const { logEntryAnnotations, editedSinceCompileStarted, compiling } =
  65. useCompileContext()
  66. const [loadingThreads] = useScopeValue<boolean>('loadingThreads')
  67. const [currentDoc] = useScopeValue<CurrentDoc | null>('editor.sharejs_doc')
  68. const [docName] = useScopeValue<string>('editor.open_doc_name')
  69. const [trackChanges] = useScopeValue<boolean>('editor.trackChanges')
  70. const { userSettings } = useUserSettingsContext()
  71. const {
  72. fontFamily,
  73. fontSize,
  74. lineHeight,
  75. overallTheme,
  76. autoComplete,
  77. editorTheme,
  78. autoPairDelimiters,
  79. mode,
  80. syntaxValidation,
  81. } = userSettings
  82. const [cursorHighlights] = useScopeValue<Record<string, Highlight[]>>(
  83. 'onlineUserCursorHighlights'
  84. )
  85. const [spellCheckLanguage] = useScopeValue<string>(
  86. 'project.spellCheckLanguage'
  87. )
  88. const [visual] = useScopeValue<boolean>('editor.showVisual')
  89. const [references] = useScopeValue<{ keys: string[] }>('$root._references')
  90. // build the translation phrases
  91. const phrases = usePhrases()
  92. const phrasesRef = useRef(phrases)
  93. // initialise the local state
  94. const themeRef = useRef({
  95. fontFamily,
  96. fontSize,
  97. lineHeight,
  98. overallTheme,
  99. editorTheme,
  100. })
  101. useEffect(() => {
  102. themeRef.current = {
  103. fontFamily,
  104. fontSize,
  105. lineHeight,
  106. overallTheme,
  107. editorTheme,
  108. }
  109. view.dispatch(
  110. setOptionsTheme({
  111. fontFamily,
  112. fontSize,
  113. lineHeight,
  114. overallTheme,
  115. })
  116. )
  117. setEditorTheme(editorTheme).then(spec => {
  118. view.dispatch(spec)
  119. })
  120. }, [view, fontFamily, fontSize, lineHeight, overallTheme, editorTheme])
  121. const settingsRef = useRef({
  122. autoComplete,
  123. autoPairDelimiters,
  124. mode,
  125. syntaxValidation,
  126. })
  127. const currentDocRef = useRef({
  128. currentDoc,
  129. trackChanges,
  130. loadingThreads,
  131. })
  132. useEffect(() => {
  133. if (currentDoc) {
  134. currentDocRef.current.currentDoc = currentDoc
  135. }
  136. }, [view, currentDoc])
  137. const docNameRef = useRef(docName)
  138. useEffect(() => {
  139. currentDocRef.current.loadingThreads = loadingThreads
  140. }, [view, loadingThreads])
  141. useEffect(() => {
  142. currentDocRef.current.trackChanges = trackChanges
  143. if (currentDoc) {
  144. if (trackChanges) {
  145. currentDoc.track_changes_as = window.user.id || 'anonymous'
  146. } else {
  147. currentDoc.track_changes_as = null
  148. }
  149. }
  150. }, [currentDoc, trackChanges])
  151. useEffect(() => {
  152. if (lineHeight && fontSize) {
  153. dispatchEditorEvent('line-height', lineHeights[lineHeight] * fontSize)
  154. }
  155. }, [lineHeight, fontSize])
  156. const spellingRef = useRef({
  157. spellCheckLanguage,
  158. })
  159. useEffect(() => {
  160. spellingRef.current = {
  161. spellCheckLanguage,
  162. }
  163. view.dispatch(setSpelling(spellingRef.current))
  164. }, [view, spellCheckLanguage])
  165. // listen to doc:after-opened, and focus the editor
  166. useEffect(() => {
  167. const listener = () => {
  168. scheduleFocus(view)
  169. }
  170. window.addEventListener('doc:after-opened', listener)
  171. return () => window.removeEventListener('doc:after-opened', listener)
  172. }, [view])
  173. // set the project metadata, mostly for use in autocomplete
  174. // TODO: read this data from the scope?
  175. const metadataRef = useRef({
  176. documents: ide.metadataManager.metadata.state.documents,
  177. references: references.keys,
  178. fileTreeData,
  179. })
  180. // listen to project metadata (docs + packages) updates
  181. useEffect(() => {
  182. const listener = (event: Event) => {
  183. metadataRef.current.documents = (
  184. event as CustomEvent<Record<string, any>>
  185. ).detail
  186. view.dispatch(setMetadata(metadataRef.current))
  187. }
  188. window.addEventListener('project:metadata', listener)
  189. return () => window.removeEventListener('project:metadata', listener)
  190. }, [view])
  191. // listen to project reference keys updates
  192. useEffect(() => {
  193. const listener = (event: Event) => {
  194. metadataRef.current.references = (event as CustomEvent<string[]>).detail
  195. view.dispatch(setMetadata(metadataRef.current))
  196. }
  197. window.addEventListener('project:references', listener)
  198. return () => window.removeEventListener('project:references', listener)
  199. }, [view])
  200. // listen to project root folder updates
  201. useEffect(() => {
  202. if (fileTreeData) {
  203. metadataRef.current.fileTreeData = fileTreeData
  204. view.dispatch(setMetadata(metadataRef.current))
  205. }
  206. }, [view, fileTreeData])
  207. const editableRef = useRef(permissions.write)
  208. const { previewByPath } = useFileTreePathContext()
  209. const showVisual = visual && isValidTexFile(docName)
  210. const visualRef = useRef({
  211. previewByPath,
  212. visual: showVisual,
  213. })
  214. const handleError = useErrorHandler()
  215. const handleException = useCallback((exception: any) => {
  216. captureException(exception, {
  217. tags: {
  218. handler: 'cm6-exception',
  219. // which editor mode is active ('visual' | 'code')
  220. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  221. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  222. ol_editor_keybindings: settingsRef.current.mode,
  223. // whether Writefull is present ('extension' | 'integration')
  224. ol_extensions_writefull: window.writefull?.type,
  225. // whether Grammarly is present
  226. ol_extensions_grammarly: grammarlyExtensionPresent(),
  227. },
  228. })
  229. }, [])
  230. // create a new state when currentDoc changes
  231. useEffect(() => {
  232. if (currentDoc) {
  233. const state = EditorState.create({
  234. doc: currentDoc.getSnapshot(),
  235. extensions: createExtensions({
  236. currentDoc: {
  237. ...currentDocRef.current,
  238. currentDoc,
  239. },
  240. docName: docNameRef.current,
  241. theme: themeRef.current,
  242. metadata: metadataRef.current,
  243. settings: settingsRef.current,
  244. phrases: phrasesRef.current,
  245. spelling: spellingRef.current,
  246. visual: visualRef.current,
  247. changeManager: createChangeManager(view, currentDoc),
  248. handleError,
  249. handleException,
  250. }),
  251. })
  252. view.setState(state)
  253. // synchronous config
  254. view.dispatch(
  255. restoreCursorPosition(state.doc, currentDoc.doc_id),
  256. setEditable(editableRef.current),
  257. setOptionsTheme(themeRef.current)
  258. )
  259. // asynchronous config
  260. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  261. view.dispatch(spec)
  262. })
  263. setKeybindings(settingsRef.current.mode).then(spec => {
  264. view.dispatch(spec)
  265. })
  266. if (!visualRef.current.visual) {
  267. window.setTimeout(() => {
  268. view.dispatch(restoreScrollPosition())
  269. view.focus()
  270. })
  271. }
  272. }
  273. // IMPORTANT: This effect must not depend on anything variable apart from currentDoc,
  274. // as the editor state is recreated when the effect runs.
  275. }, [view, currentDoc, handleError, handleException])
  276. useEffect(() => {
  277. if (docName) {
  278. docNameRef.current = docName
  279. view.dispatch(
  280. setDocName(docNameRef.current),
  281. setLanguage(
  282. docNameRef.current,
  283. metadataRef.current,
  284. settingsRef.current.syntaxValidation
  285. )
  286. )
  287. }
  288. }, [view, docName])
  289. useEffect(() => {
  290. visualRef.current.visual = showVisual
  291. view.dispatch(setVisual(visualRef.current))
  292. view.dispatch({
  293. effects: EditorView.scrollIntoView(view.state.selection.main.head),
  294. })
  295. // clear performance measures and marks when switching between Source and Rich Text
  296. window.dispatchEvent(new Event('editor:visual-switch'))
  297. }, [view, showVisual])
  298. useEffect(() => {
  299. visualRef.current.previewByPath = previewByPath
  300. view.dispatch(setVisual(visualRef.current))
  301. }, [view, previewByPath])
  302. useEffect(() => {
  303. editableRef.current = permissions.write
  304. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  305. }, [view, permissions.write])
  306. useEffect(() => {
  307. phrasesRef.current = phrases
  308. view.dispatch(setPhrases(phrases))
  309. }, [view, phrases])
  310. // listen to editor settings updates
  311. useEffect(() => {
  312. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  313. view.dispatch(setAutoPair(autoPairDelimiters))
  314. }, [view, autoPairDelimiters])
  315. useEffect(() => {
  316. settingsRef.current.autoComplete = autoComplete
  317. view.dispatch(setAutoComplete(autoComplete))
  318. }, [view, autoComplete])
  319. useEffect(() => {
  320. settingsRef.current.mode = mode
  321. setKeybindings(mode).then(spec => {
  322. view.dispatch(spec)
  323. })
  324. }, [view, mode])
  325. useEffect(() => {
  326. settingsRef.current.syntaxValidation = syntaxValidation
  327. view.dispatch(setSyntaxValidation(syntaxValidation))
  328. }, [view, syntaxValidation])
  329. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  330. const handleGoToLine = useCallback(
  331. (event, lineNumber, columnNumber, syncToPdf) => {
  332. setCursorLineAndScroll(view, lineNumber, columnNumber)
  333. if (syncToPdf) {
  334. emitSyncToPdf()
  335. }
  336. },
  337. [emitSyncToPdf, view]
  338. )
  339. // select and scroll to position on editor:gotoLine event (from synctex)
  340. useScopeEventListener('editor:gotoLine', handleGoToLine)
  341. const handleGoToOffset = useCallback(
  342. (event, offset) => {
  343. setCursorPositionAndScroll(view, offset)
  344. },
  345. [view]
  346. )
  347. // select and scroll to position on editor:gotoOffset event (from review panel)
  348. useScopeEventListener('editor:gotoOffset', handleGoToOffset)
  349. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  350. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  351. const handleCursorUpdate = useCallback(
  352. (event: CustomEvent) => {
  353. dispatchCursorUpdate(event.detail)
  354. },
  355. [dispatchCursorUpdate]
  356. )
  357. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  358. useEventListener('cursor:editor:update', handleCursorUpdate)
  359. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  360. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  361. const handleScrollUpdate = useCallback(
  362. (event: CustomEvent) => {
  363. dispatchScrollUpdate(event.detail)
  364. },
  365. [dispatchScrollUpdate]
  366. )
  367. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  368. useEventListener('scroll:editor:update', handleScrollUpdate)
  369. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  370. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  371. // but we don't want to display the compile log diagnostics from the previous compile.
  372. const enableCompileLogLinter =
  373. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  374. // store enableCompileLogLinter in a ref for use in useEffect
  375. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  376. useEffect(() => {
  377. enableCompileLogLinterRef.current = enableCompileLogLinter
  378. }, [enableCompileLogLinter])
  379. // enable/disable the compile log linter as appropriate
  380. useEffect(() => {
  381. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  382. window.setTimeout(() => {
  383. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  384. }, 0)
  385. }, [view, enableCompileLogLinter])
  386. // set the compile log annotations when they change
  387. useEffect(() => {
  388. if (currentDoc && logEntryAnnotations) {
  389. const annotations = logEntryAnnotations[currentDoc.doc_id]
  390. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  391. window.setTimeout(() => {
  392. view.dispatch(
  393. setAnnotations(view.state.doc, annotations || []),
  394. // reconfigure the compile log lint source, so it runs once with the new data
  395. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  396. )
  397. })
  398. }
  399. }, [view, currentDoc, logEntryAnnotations])
  400. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  401. cursorHighlights: [],
  402. })
  403. useEffect(() => {
  404. if (cursorHighlights && currentDoc) {
  405. const items = cursorHighlights[currentDoc.doc_id]
  406. highlightsRef.current.cursorHighlights = items
  407. window.setTimeout(() => {
  408. view.dispatch(setCursorHighlights(items))
  409. })
  410. }
  411. }, [view, cursorHighlights, currentDoc])
  412. const handleAddLearnedWords = useCallback(
  413. (event: CustomEvent<string>) => {
  414. // If the word addition is from adding the word to the dictionary via the
  415. // editor, there will be a transaction running now so wait for that to
  416. // finish before starting a new one
  417. window.setTimeout(() => {
  418. view.dispatch(addLearnedWord(spellCheckLanguage, event.detail))
  419. }, 0)
  420. },
  421. [spellCheckLanguage, view]
  422. )
  423. useEventListener('learnedWords:add', handleAddLearnedWords)
  424. const handleRemoveLearnedWords = useCallback(
  425. (event: CustomEvent<string>) => {
  426. view.dispatch(removeLearnedWord(spellCheckLanguage, event.detail))
  427. },
  428. [spellCheckLanguage, view]
  429. )
  430. useEventListener('learnedWords:remove', handleRemoveLearnedWords)
  431. const handleResetLearnedWords = useCallback(() => {
  432. view.dispatch(resetLearnedWords())
  433. }, [view])
  434. useEventListener('learnedWords:reset', handleResetLearnedWords)
  435. }
  436. export default useCodeMirrorScope
  437. const scheduleFocus = (view: EditorView) => {
  438. window.setTimeout(() => {
  439. view.focus()
  440. }, 0)
  441. }