use-codemirror-scope.ts 17 KB

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