use-codemirror-scope.ts 18 KB

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