use-codemirror-scope.ts 19 KB

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