use-codemirror-scope.ts 16 KB

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