use-codemirror-scope.ts 17 KB

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