use-codemirror-scope.ts 17 KB

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