use-codemirror-scope.ts 19 KB

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