use-codemirror-scope.ts 16 KB

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