use-codemirror-scope.ts 17 KB

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