use-codemirror-scope.ts 19 KB

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