use-codemirror-scope.ts 18 KB

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