use-codemirror-scope.ts 18 KB

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