use-codemirror-scope.ts 18 KB

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