use-codemirror-scope.ts 19 KB

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