use-codemirror-scope.ts 17 KB

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