use-codemirror-scope.ts 17 KB

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