use-codemirror-scope.ts 18 KB

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