use-codemirror-scope.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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 { setEditorTheme, setOptionsTheme } from '../extensions/theme'
  9. import {
  10. restoreCursorPosition,
  11. setCursorLineAndScroll,
  12. setCursorPositionAndScroll,
  13. } from '../extensions/cursor-position'
  14. import {
  15. setAnnotations,
  16. showCompileLogDiagnostics,
  17. } from '../extensions/annotations'
  18. import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
  19. import { setCursorHighlights } from '../extensions/cursor-highlights'
  20. import {
  21. setLanguage,
  22. setMetadata,
  23. setSyntaxValidation,
  24. } from '../extensions/language'
  25. import { restoreScrollPosition } from '../extensions/scroll-position'
  26. import { setEditable } from '../extensions/editable'
  27. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  28. import { setAutoPair } from '../extensions/auto-pair'
  29. import { setAutoComplete } from '../extensions/auto-complete'
  30. import { usePhrases } from './use-phrases'
  31. import { setPhrases } from '../extensions/phrases'
  32. import { setSpellCheckLanguage } from '../extensions/spelling'
  33. import {
  34. createChangeManager,
  35. dispatchEditorEvent,
  36. reviewPanelToggled,
  37. } from '../extensions/changes/change-manager'
  38. import { setKeybindings } from '../extensions/keybindings'
  39. import { Highlight } from '../../../../../types/highlight'
  40. import { EditorView } from '@codemirror/view'
  41. import { useErrorHandler } from 'react-error-boundary'
  42. import { setVisual } from '../extensions/visual/visual'
  43. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  44. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  45. import { setDocName } from '@/features/source-editor/extensions/doc-name'
  46. import { isValidTeXFile } from '@/main/is-valid-tex-file'
  47. import { captureException } from '@/infrastructure/error-reporter'
  48. import grammarlyExtensionPresent from '@/shared/utils/grammarly'
  49. import { useLayoutContext } from '@/shared/context/layout-context'
  50. import { debugConsole } from '@/utils/debugging'
  51. import { useMetadataContext } from '@/features/ide-react/context/metadata-context'
  52. import { useUserContext } from '@/shared/context/user-context'
  53. import { useReferencesContext } from '@/features/ide-react/context/references-context'
  54. import { setMathPreview } from '@/features/source-editor/extensions/math-preview'
  55. import { useRangesContext } from '@/features/review-panel-new/context/ranges-context'
  56. import { updateRanges } from '@/features/source-editor/extensions/ranges'
  57. import { useThreadsContext } from '@/features/review-panel-new/context/threads-context'
  58. import { useHunspell } from '@/features/source-editor/hooks/use-hunspell'
  59. import { Permissions } from '@/features/ide-react/types/permissions'
  60. import { lineHeights } from '@/shared/utils/styles'
  61. import { useEditorManagerContext } from '@/features/ide-react/context/editor-manager-context'
  62. import { useOnlineUsersContext } from '@/features/ide-react/context/online-users-context'
  63. function useCodeMirrorScope(view: EditorView) {
  64. const { fileTreeData } = useFileTreeData()
  65. const [permissions] = useScopeValue<Permissions>('permissions')
  66. // set up scope listeners
  67. const { logEntryAnnotations, editedSinceCompileStarted, compiling } =
  68. useCompileContext()
  69. const { reviewPanelOpen, miniReviewPanelVisible } = useLayoutContext()
  70. const { currentDocument, openDocName, trackChanges } =
  71. useEditorManagerContext()
  72. const metadata = useMetadataContext()
  73. const [loadingThreads] = useScopeValue<boolean>('loadingThreads')
  74. const { id: userId } = useUserContext()
  75. const { userSettings } = useUserSettingsContext()
  76. const {
  77. fontFamily,
  78. fontSize,
  79. lineHeight,
  80. overallTheme,
  81. autoComplete,
  82. editorTheme,
  83. autoPairDelimiters,
  84. mode,
  85. syntaxValidation,
  86. mathPreview,
  87. referencesSearchMode,
  88. } = userSettings
  89. const { onlineUserCursorHighlights } = useOnlineUsersContext()
  90. let [spellCheckLanguage] = useScopeValue<string>('project.spellCheckLanguage')
  91. // spell check is off when read-only
  92. if (!permissions.write && !permissions.trackedWrite) {
  93. spellCheckLanguage = ''
  94. }
  95. const [projectFeatures] =
  96. useScopeValue<Record<string, boolean | string | number | undefined>>(
  97. 'project.features'
  98. )
  99. const hunspellManager = useHunspell(spellCheckLanguage)
  100. const [visual] = useScopeValue<boolean>('editor.showVisual')
  101. const { referenceKeys } = useReferencesContext()
  102. const ranges = useRangesContext()
  103. const threads = useThreadsContext()
  104. // build the translation phrases
  105. const phrases = usePhrases()
  106. const phrasesRef = useRef(phrases)
  107. // initialise the local state
  108. const themeRef = useRef({
  109. fontFamily,
  110. fontSize,
  111. lineHeight,
  112. overallTheme,
  113. editorTheme,
  114. })
  115. useEffect(() => {
  116. themeRef.current = {
  117. fontFamily,
  118. fontSize,
  119. lineHeight,
  120. overallTheme,
  121. editorTheme,
  122. }
  123. view.dispatch(
  124. setOptionsTheme({
  125. fontFamily,
  126. fontSize,
  127. lineHeight,
  128. overallTheme,
  129. })
  130. )
  131. setEditorTheme(editorTheme).then(spec => {
  132. view.dispatch(spec)
  133. })
  134. }, [view, fontFamily, fontSize, lineHeight, overallTheme, editorTheme])
  135. const settingsRef = useRef({
  136. autoComplete,
  137. autoPairDelimiters,
  138. mode,
  139. syntaxValidation,
  140. mathPreview,
  141. referencesSearchMode,
  142. })
  143. const currentDocRef = useRef({
  144. currentDocument,
  145. trackChanges,
  146. loadingThreads,
  147. })
  148. useEffect(() => {
  149. if (currentDocument) {
  150. currentDocRef.current.currentDocument = currentDocument
  151. }
  152. }, [view, currentDocument])
  153. useEffect(() => {
  154. if (ranges && threads) {
  155. window.setTimeout(() => {
  156. view.dispatch(updateRanges({ ranges, threads }))
  157. })
  158. }
  159. }, [view, ranges, threads])
  160. const docNameRef = useRef(openDocName)
  161. useEffect(() => {
  162. currentDocRef.current.loadingThreads = loadingThreads
  163. }, [view, loadingThreads])
  164. useEffect(() => {
  165. currentDocRef.current.trackChanges = trackChanges
  166. if (currentDocument) {
  167. if (trackChanges) {
  168. currentDocument.track_changes_as = userId || 'anonymous'
  169. } else {
  170. currentDocument.track_changes_as = null
  171. }
  172. }
  173. }, [userId, currentDocument, trackChanges])
  174. useEffect(() => {
  175. if (lineHeight && fontSize) {
  176. dispatchEditorEvent('line-height', lineHeights[lineHeight] * fontSize)
  177. }
  178. }, [lineHeight, fontSize])
  179. const spellingRef = useRef({
  180. spellCheckLanguage,
  181. hunspellManager,
  182. })
  183. useEffect(() => {
  184. spellingRef.current = {
  185. spellCheckLanguage,
  186. hunspellManager,
  187. }
  188. window.setTimeout(() => {
  189. view.dispatch(setSpellCheckLanguage(spellingRef.current))
  190. })
  191. }, [view, spellCheckLanguage, hunspellManager])
  192. const projectFeaturesRef = useRef(projectFeatures)
  193. // listen to doc:after-opened, and focus the editor if it's not a new doc
  194. useEffect(() => {
  195. const listener: EventListener = event => {
  196. const { isNewDoc } = (event as CustomEvent<{ isNewDoc: boolean }>).detail
  197. if (!isNewDoc) {
  198. window.setTimeout(() => {
  199. view.focus()
  200. }, 0)
  201. }
  202. }
  203. window.addEventListener('doc:after-opened', listener)
  204. return () => window.removeEventListener('doc:after-opened', listener)
  205. }, [view])
  206. // set the project metadata, mostly for use in autocomplete
  207. // TODO: read this data from the scope?
  208. const metadataRef = useRef({
  209. ...metadata,
  210. referenceKeys,
  211. fileTreeData,
  212. })
  213. // listen to project metadata (commands, labels and package names) updates
  214. useEffect(() => {
  215. metadataRef.current = { ...metadataRef.current, ...metadata }
  216. window.setTimeout(() => {
  217. view.dispatch(setMetadata(metadataRef.current))
  218. })
  219. }, [view, metadata])
  220. // listen to project reference keys updates
  221. useEffect(() => {
  222. metadataRef.current.referenceKeys = referenceKeys
  223. window.setTimeout(() => {
  224. view.dispatch(setMetadata(metadataRef.current))
  225. })
  226. }, [view, referenceKeys])
  227. // listen to project root folder updates
  228. useEffect(() => {
  229. if (fileTreeData) {
  230. metadataRef.current.fileTreeData = fileTreeData
  231. window.setTimeout(() => {
  232. view.dispatch(setMetadata(metadataRef.current))
  233. })
  234. }
  235. }, [view, fileTreeData])
  236. const editableRef = useRef(permissions.write || permissions.trackedWrite)
  237. const { previewByPath } = useFileTreePathContext()
  238. const showVisual = visual && !!openDocName && isValidTeXFile(openDocName)
  239. const visualRef = useRef({
  240. previewByPath,
  241. visual: showVisual,
  242. })
  243. const handleError = useErrorHandler()
  244. const handleException = useCallback((exception: any) => {
  245. captureException(exception, {
  246. tags: {
  247. handler: 'cm6-exception',
  248. // which editor mode is active ('visual' | 'code')
  249. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  250. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  251. ol_editor_keybindings: settingsRef.current.mode,
  252. // whether Writefull is present ('extension' | 'integration' | 'none')
  253. ol_extensions_writefull: window.writefull?.type ?? 'none',
  254. // whether Grammarly is present
  255. ol_extensions_grammarly: grammarlyExtensionPresent(),
  256. },
  257. })
  258. }, [])
  259. // create a new state when currentDocument changes
  260. useEffect(() => {
  261. if (currentDocument) {
  262. debugConsole.log('creating new editor state')
  263. const state = EditorState.create({
  264. doc: currentDocument.getSnapshot(),
  265. extensions: createExtensions({
  266. currentDoc: {
  267. ...currentDocRef.current,
  268. currentDoc: currentDocument,
  269. },
  270. docName: docNameRef.current,
  271. theme: themeRef.current,
  272. metadata: metadataRef.current,
  273. settings: settingsRef.current,
  274. phrases: phrasesRef.current,
  275. spelling: spellingRef.current,
  276. visual: visualRef.current,
  277. projectFeatures: projectFeaturesRef.current,
  278. changeManager: createChangeManager(view, currentDocument),
  279. handleError,
  280. handleException,
  281. }),
  282. })
  283. view.setState(state)
  284. // synchronous config
  285. view.dispatch(
  286. restoreCursorPosition(state.doc, currentDocument.doc_id),
  287. setEditable(editableRef.current),
  288. setOptionsTheme(themeRef.current)
  289. )
  290. // asynchronous config
  291. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  292. view.dispatch(spec)
  293. })
  294. setKeybindings(settingsRef.current.mode).then(spec => {
  295. view.dispatch(spec)
  296. })
  297. if (!visualRef.current.visual) {
  298. window.setTimeout(() => {
  299. view.dispatch(restoreScrollPosition())
  300. view.focus()
  301. })
  302. }
  303. }
  304. // IMPORTANT: This effect must not depend on anything variable apart from currentDocument,
  305. // as the editor state is recreated when the effect runs.
  306. }, [view, currentDocument, handleError, handleException])
  307. useEffect(() => {
  308. if (openDocName) {
  309. docNameRef.current = openDocName
  310. window.setTimeout(() => {
  311. view.dispatch(
  312. setDocName(openDocName),
  313. setLanguage(
  314. openDocName,
  315. metadataRef.current,
  316. settingsRef.current.syntaxValidation
  317. )
  318. )
  319. })
  320. }
  321. }, [view, openDocName])
  322. useEffect(() => {
  323. visualRef.current.visual = showVisual
  324. window.setTimeout(() => {
  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. })
  332. }, [view, showVisual])
  333. useEffect(() => {
  334. visualRef.current.previewByPath = previewByPath
  335. window.setTimeout(() => {
  336. view.dispatch(setVisual(visualRef.current))
  337. })
  338. }, [view, previewByPath])
  339. useEffect(() => {
  340. editableRef.current = permissions.write || permissions.trackedWrite
  341. window.setTimeout(() => {
  342. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  343. })
  344. }, [view, permissions.write, permissions.trackedWrite])
  345. useEffect(() => {
  346. phrasesRef.current = phrases
  347. window.setTimeout(() => {
  348. view.dispatch(setPhrases(phrases))
  349. })
  350. }, [view, phrases])
  351. // listen to editor settings updates
  352. useEffect(() => {
  353. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  354. window.setTimeout(() => {
  355. view.dispatch(setAutoPair(autoPairDelimiters))
  356. })
  357. }, [view, autoPairDelimiters])
  358. useEffect(() => {
  359. settingsRef.current.autoComplete = autoComplete
  360. window.setTimeout(() => {
  361. view.dispatch(
  362. setAutoComplete({
  363. enabled: autoComplete,
  364. projectFeatures: projectFeaturesRef.current,
  365. referencesSearchMode: settingsRef.current.referencesSearchMode,
  366. })
  367. )
  368. })
  369. }, [view, autoComplete])
  370. useEffect(() => {
  371. settingsRef.current.mode = mode
  372. setKeybindings(mode).then(spec => {
  373. window.setTimeout(() => {
  374. view.dispatch(spec)
  375. })
  376. })
  377. }, [view, mode])
  378. useEffect(() => {
  379. settingsRef.current.syntaxValidation = syntaxValidation
  380. window.setTimeout(() => {
  381. view.dispatch(setSyntaxValidation(syntaxValidation))
  382. })
  383. }, [view, syntaxValidation])
  384. useEffect(() => {
  385. settingsRef.current.mathPreview = mathPreview
  386. window.setTimeout(() => {
  387. view.dispatch(setMathPreview(mathPreview))
  388. })
  389. }, [view, mathPreview])
  390. useEffect(() => {
  391. settingsRef.current.referencesSearchMode = referencesSearchMode
  392. }, [referencesSearchMode])
  393. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  394. // select and scroll to position on editor:gotoLine event (from synctex)
  395. useScopeEventListener(
  396. 'editor:gotoLine',
  397. useCallback(
  398. (_event, options) => {
  399. setCursorLineAndScroll(
  400. view,
  401. options.gotoLine,
  402. options.gotoColumn,
  403. options.selectText
  404. )
  405. if (options.syncToPdf) {
  406. emitSyncToPdf()
  407. }
  408. },
  409. [emitSyncToPdf, view]
  410. )
  411. )
  412. // select and scroll to position on editor:gotoOffset event (from review panel)
  413. useScopeEventListener(
  414. 'editor:gotoOffset',
  415. useCallback(
  416. (_event, options) => {
  417. setCursorPositionAndScroll(view, options.gotoOffset)
  418. },
  419. [view]
  420. )
  421. )
  422. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  423. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  424. const handleCursorUpdate = useCallback(
  425. (event: CustomEvent) => {
  426. dispatchCursorUpdate(event.detail)
  427. },
  428. [dispatchCursorUpdate]
  429. )
  430. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  431. useEventListener('cursor:editor:update', handleCursorUpdate)
  432. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  433. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  434. const handleScrollUpdate = useCallback(
  435. (event: CustomEvent) => {
  436. dispatchScrollUpdate(event.detail)
  437. },
  438. [dispatchScrollUpdate]
  439. )
  440. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  441. useEventListener('scroll:editor:update', handleScrollUpdate)
  442. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  443. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  444. // but we don't want to display the compile log diagnostics from the previous compile.
  445. const enableCompileLogLinter =
  446. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  447. // store enableCompileLogLinter in a ref for use in useEffect
  448. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  449. useEffect(() => {
  450. enableCompileLogLinterRef.current = enableCompileLogLinter
  451. }, [enableCompileLogLinter])
  452. // enable/disable the compile log linter as appropriate
  453. useEffect(() => {
  454. window.setTimeout(() => {
  455. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  456. })
  457. }, [view, enableCompileLogLinter])
  458. // set the compile log annotations when they change
  459. useEffect(() => {
  460. if (currentDocument && logEntryAnnotations) {
  461. const annotations = logEntryAnnotations[currentDocument.doc_id]
  462. window.setTimeout(() => {
  463. view.dispatch(
  464. setAnnotations(view.state, annotations || []),
  465. // reconfigure the compile log lint source, so it runs once with the new data
  466. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  467. )
  468. })
  469. }
  470. }, [view, currentDocument, logEntryAnnotations])
  471. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  472. cursorHighlights: [],
  473. })
  474. useEffect(() => {
  475. if (onlineUserCursorHighlights && currentDocument) {
  476. const items = onlineUserCursorHighlights[currentDocument.doc_id]
  477. highlightsRef.current.cursorHighlights = items
  478. window.setTimeout(() => {
  479. view.dispatch(setCursorHighlights(items))
  480. })
  481. }
  482. }, [view, onlineUserCursorHighlights, currentDocument])
  483. useEventListener(
  484. 'editor:focus',
  485. useCallback(() => {
  486. view.focus()
  487. }, [view])
  488. )
  489. useEffect(() => {
  490. window.setTimeout(() => {
  491. view.dispatch(reviewPanelToggled())
  492. })
  493. }, [reviewPanelOpen, miniReviewPanelVisible, view])
  494. }
  495. export default useCodeMirrorScope