use-codemirror-scope.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 { restoreScrollPosition } from '../extensions/scroll-position'
  30. import { setEditable } from '../extensions/editable'
  31. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  32. import { setAutoPair } from '../extensions/auto-pair'
  33. import { setAutoComplete } from '../extensions/auto-complete'
  34. import { usePhrases } from './use-phrases'
  35. import { setPhrases } from '../extensions/phrases'
  36. import {
  37. addLearnedWord,
  38. removeLearnedWord,
  39. resetLearnedWords,
  40. setSpelling,
  41. } from '../extensions/spelling'
  42. import {
  43. createChangeManager,
  44. dispatchEditorEvent,
  45. reviewPanelToggled,
  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. import { useLayoutContext } from '@/shared/context/layout-context'
  60. import { debugConsole } from '@/utils/debugging'
  61. import { useMetadataContext } from '@/features/ide-react/context/metadata-context'
  62. import { useUserContext } from '@/shared/context/user-context'
  63. import { useReferencesContext } from '@/features/ide-react/context/references-context'
  64. function useCodeMirrorScope(view: EditorView) {
  65. const { fileTreeData } = useFileTreeData()
  66. const [permissions] = useScopeValue<{ write: boolean }>('permissions')
  67. // set up scope listeners
  68. const { logEntryAnnotations, editedSinceCompileStarted, compiling } =
  69. useCompileContext()
  70. const { reviewPanelOpen, miniReviewPanelVisible } = useLayoutContext()
  71. const metadata = useMetadataContext()
  72. const [loadingThreads] = useScopeValue<boolean>('loadingThreads')
  73. const [currentDoc] = useScopeValue<DocumentContainer | null>(
  74. 'editor.sharejs_doc'
  75. )
  76. const [docName] = useScopeValue<string>('editor.open_doc_name')
  77. const [trackChanges] = useScopeValue<boolean>('editor.trackChanges')
  78. const { id: userId } = useUserContext()
  79. const { userSettings } = useUserSettingsContext()
  80. const {
  81. fontFamily,
  82. fontSize,
  83. lineHeight,
  84. overallTheme,
  85. autoComplete,
  86. editorTheme,
  87. autoPairDelimiters,
  88. mode,
  89. syntaxValidation,
  90. } = userSettings
  91. const [cursorHighlights] = useScopeValue<Record<string, Highlight[]>>(
  92. 'onlineUserCursorHighlights'
  93. )
  94. const [spellCheckLanguage] = useScopeValue<string>(
  95. 'project.spellCheckLanguage'
  96. )
  97. const [visual] = useScopeValue<boolean>('editor.showVisual')
  98. const { referenceKeys } = useReferencesContext()
  99. // build the translation phrases
  100. const phrases = usePhrases()
  101. const phrasesRef = useRef(phrases)
  102. // initialise the local state
  103. const themeRef = useRef({
  104. fontFamily,
  105. fontSize,
  106. lineHeight,
  107. overallTheme,
  108. editorTheme,
  109. })
  110. useEffect(() => {
  111. themeRef.current = {
  112. fontFamily,
  113. fontSize,
  114. lineHeight,
  115. overallTheme,
  116. editorTheme,
  117. }
  118. view.dispatch(
  119. setOptionsTheme({
  120. fontFamily,
  121. fontSize,
  122. lineHeight,
  123. overallTheme,
  124. })
  125. )
  126. setEditorTheme(editorTheme).then(spec => {
  127. view.dispatch(spec)
  128. })
  129. }, [view, fontFamily, fontSize, lineHeight, overallTheme, editorTheme])
  130. const settingsRef = useRef({
  131. autoComplete,
  132. autoPairDelimiters,
  133. mode,
  134. syntaxValidation,
  135. })
  136. const currentDocRef = useRef({
  137. currentDoc,
  138. trackChanges,
  139. loadingThreads,
  140. })
  141. useEffect(() => {
  142. if (currentDoc) {
  143. currentDocRef.current.currentDoc = currentDoc
  144. }
  145. }, [view, currentDoc])
  146. const docNameRef = useRef(docName)
  147. useEffect(() => {
  148. currentDocRef.current.loadingThreads = loadingThreads
  149. }, [view, loadingThreads])
  150. useEffect(() => {
  151. currentDocRef.current.trackChanges = trackChanges
  152. if (currentDoc) {
  153. if (trackChanges) {
  154. currentDoc.track_changes_as = userId || 'anonymous'
  155. } else {
  156. currentDoc.track_changes_as = null
  157. }
  158. }
  159. }, [userId, currentDoc, trackChanges])
  160. useEffect(() => {
  161. if (lineHeight && fontSize) {
  162. dispatchEditorEvent('line-height', lineHeights[lineHeight] * fontSize)
  163. }
  164. }, [lineHeight, fontSize])
  165. const spellingRef = useRef({
  166. spellCheckLanguage,
  167. })
  168. useEffect(() => {
  169. spellingRef.current = {
  170. spellCheckLanguage,
  171. }
  172. view.dispatch(setSpelling(spellingRef.current))
  173. }, [view, spellCheckLanguage])
  174. // listen to doc:after-opened, and focus the editor
  175. useEffect(() => {
  176. const listener = () => {
  177. scheduleFocus(view)
  178. }
  179. window.addEventListener('doc:after-opened', listener)
  180. return () => window.removeEventListener('doc:after-opened', listener)
  181. }, [view])
  182. // set the project metadata, mostly for use in autocomplete
  183. // TODO: read this data from the scope?
  184. const metadataRef = useRef({
  185. ...metadata,
  186. referenceKeys,
  187. fileTreeData,
  188. })
  189. // listen to project metadata (commands, labels and package names) updates
  190. useEffect(() => {
  191. metadataRef.current = { ...metadataRef.current, ...metadata }
  192. view.dispatch(setMetadata(metadataRef.current))
  193. }, [view, metadata])
  194. // listen to project reference keys updates
  195. useEffect(() => {
  196. metadataRef.current.referenceKeys = referenceKeys
  197. view.dispatch(setMetadata(metadataRef.current))
  198. }, [view, referenceKeys])
  199. // listen to project root folder updates
  200. useEffect(() => {
  201. if (fileTreeData) {
  202. metadataRef.current.fileTreeData = fileTreeData
  203. view.dispatch(setMetadata(metadataRef.current))
  204. }
  205. }, [view, fileTreeData])
  206. const editableRef = useRef(permissions.write)
  207. const { previewByPath } = useFileTreePathContext()
  208. const showVisual = visual && isValidTexFile(docName)
  209. const visualRef = useRef({
  210. previewByPath,
  211. visual: showVisual,
  212. })
  213. const handleError = useErrorHandler()
  214. const handleException = useCallback((exception: any) => {
  215. captureException(exception, {
  216. tags: {
  217. handler: 'cm6-exception',
  218. // which editor mode is active ('visual' | 'code')
  219. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  220. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  221. ol_editor_keybindings: settingsRef.current.mode,
  222. // whether Writefull is present ('extension' | 'integration' | 'none')
  223. ol_extensions_writefull: window.writefull?.type ?? 'none',
  224. // whether Grammarly is present
  225. ol_extensions_grammarly: grammarlyExtensionPresent(),
  226. },
  227. })
  228. }, [])
  229. // create a new state when currentDoc changes
  230. useEffect(() => {
  231. if (currentDoc) {
  232. debugConsole.log('creating new editor state')
  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. useEffect(() => {
  436. view.dispatch(reviewPanelToggled())
  437. }, [reviewPanelOpen, miniReviewPanelVisible, view])
  438. }
  439. export default useCodeMirrorScope
  440. const scheduleFocus = (view: EditorView) => {
  441. window.setTimeout(() => {
  442. view.focus()
  443. }, 0)
  444. }