use-codemirror-scope.ts 18 KB

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