use-codemirror-scope.ts 17 KB

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