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