use-codemirror-scope.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 } = 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. fileTreeData,
  199. })
  200. // listen to project metadata (commands, labels and package names) updates
  201. useEffect(() => {
  202. metadataRef.current = { ...metadataRef.current, ...metadata }
  203. window.setTimeout(() => {
  204. view.dispatch(setMetadata(metadataRef.current))
  205. })
  206. }, [view, metadata])
  207. // listen to project reference keys updates
  208. useEffect(() => {
  209. metadataRef.current.referenceKeys = referenceKeys
  210. window.setTimeout(() => {
  211. view.dispatch(setMetadata(metadataRef.current))
  212. })
  213. }, [view, referenceKeys])
  214. // listen to project root folder updates
  215. useEffect(() => {
  216. if (fileTreeData) {
  217. metadataRef.current.fileTreeData = fileTreeData
  218. window.setTimeout(() => {
  219. view.dispatch(setMetadata(metadataRef.current))
  220. })
  221. }
  222. }, [view, fileTreeData])
  223. const editableRef = useRef(permissions.write || permissions.trackedWrite)
  224. const { previewByPath } = useFileTreePathContext()
  225. const showVisual = visual && !!openDocName && isValidTeXFile(openDocName)
  226. const visualRef = useRef({
  227. previewByPath,
  228. visual: showVisual,
  229. })
  230. // Persist the search query in this hook when the document changes by keeping
  231. // a reference to the search query in sync with the editor state
  232. const searchQueryRef = useRef<SearchQuery | null>(null)
  233. useEventListener(
  234. 'search-panel-before-doc-change',
  235. useCallback((event: CustomEvent) => {
  236. searchQueryRef.current = event.detail
  237. }, [])
  238. )
  239. const { showBoundary } = useErrorBoundary()
  240. const handleException = useCallback((exception: any) => {
  241. captureException(exception, {
  242. tags: {
  243. handler: 'cm6-exception',
  244. // which editor mode is active ('visual' | 'code')
  245. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  246. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  247. ol_editor_keybindings: settingsRef.current.mode,
  248. // whether Writefull is present ('extension' | 'integration' | 'none')
  249. ol_extensions_writefull: window.writefull?.type ?? 'none',
  250. // whether Grammarly is present
  251. ol_extensions_grammarly: grammarlyExtensionPresent(),
  252. },
  253. })
  254. }, [])
  255. // create a new state when currentDocument changes
  256. useEffect(() => {
  257. if (currentDocument) {
  258. debugConsole.log('creating new editor state')
  259. // Warn any interested extension that the document is about to change,
  260. // allowing it to perform any necessary actions before creating the new
  261. // state. destroy() is too late because the new state is already created
  262. view.dispatch({
  263. effects: beforeChangeDocEffect.of(null),
  264. })
  265. const state = EditorState.create({
  266. doc: currentDocument.getSnapshot(),
  267. extensions: createExtensions({
  268. currentDoc: {
  269. ...currentDocRef.current,
  270. currentDoc: currentDocument,
  271. },
  272. docName: docNameRef.current,
  273. theme: themeRef.current,
  274. metadata: metadataRef.current,
  275. settings: settingsRef.current,
  276. phrases: phrasesRef.current,
  277. spelling: spellingRef.current,
  278. visual: visualRef.current,
  279. projectFeatures: projectFeaturesRef.current,
  280. initialSearchQuery: searchQueryRef.current,
  281. showBoundary,
  282. handleException,
  283. }),
  284. })
  285. view.setState(state)
  286. // synchronous config
  287. view.dispatch(
  288. restoreCursorPosition(state.doc, currentDocument.doc_id),
  289. setEditable(editableRef.current),
  290. setOptionsTheme(themeRef.current)
  291. )
  292. // asynchronous config
  293. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  294. view.dispatch(spec)
  295. })
  296. setKeybindings(settingsRef.current.mode).then(spec => {
  297. view.dispatch(spec)
  298. })
  299. if (!visualRef.current.visual) {
  300. window.setTimeout(() => {
  301. view.dispatch(restoreScrollPosition())
  302. view.focus()
  303. })
  304. }
  305. }
  306. // IMPORTANT: This effect must not depend on anything variable apart from currentDocument,
  307. // as the editor state is recreated when the effect runs.
  308. }, [view, currentDocument, showBoundary, handleException])
  309. useEffect(() => {
  310. if (openDocName) {
  311. docNameRef.current = openDocName
  312. window.setTimeout(() => {
  313. view.dispatch(
  314. setDocName(openDocName),
  315. setLanguage(
  316. openDocName,
  317. metadataRef.current,
  318. settingsRef.current.syntaxValidation
  319. )
  320. )
  321. })
  322. }
  323. }, [view, openDocName])
  324. useEffect(() => {
  325. visualRef.current.visual = showVisual
  326. window.setTimeout(() => {
  327. view.dispatch(setVisual(visualRef.current))
  328. view.dispatch({
  329. effects: EditorView.scrollIntoView(view.state.selection.main.head),
  330. })
  331. // clear performance measures and marks when switching between Source and Rich Text
  332. window.dispatchEvent(new Event('editor:visual-switch'))
  333. })
  334. }, [view, showVisual])
  335. useEffect(() => {
  336. visualRef.current.previewByPath = previewByPath
  337. window.setTimeout(() => {
  338. view.dispatch(setVisual(visualRef.current))
  339. })
  340. }, [view, previewByPath])
  341. useEffect(() => {
  342. editableRef.current = permissions.write || permissions.trackedWrite
  343. window.setTimeout(() => {
  344. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  345. })
  346. }, [view, permissions.write, permissions.trackedWrite])
  347. useEffect(() => {
  348. phrasesRef.current = phrases
  349. window.setTimeout(() => {
  350. view.dispatch(setPhrases(phrases))
  351. })
  352. }, [view, phrases])
  353. // listen to editor settings updates
  354. useEffect(() => {
  355. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  356. window.setTimeout(() => {
  357. view.dispatch(setAutoPair(autoPairDelimiters))
  358. })
  359. }, [view, autoPairDelimiters])
  360. useEffect(() => {
  361. settingsRef.current.autoComplete = autoComplete
  362. window.setTimeout(() => {
  363. view.dispatch(
  364. setAutoComplete({
  365. enabled: autoComplete,
  366. projectFeatures: projectFeaturesRef.current,
  367. referencesSearchMode: settingsRef.current.referencesSearchMode,
  368. })
  369. )
  370. })
  371. }, [view, autoComplete])
  372. useEffect(() => {
  373. settingsRef.current.mode = mode
  374. setKeybindings(mode).then(spec => {
  375. window.setTimeout(() => {
  376. view.dispatch(spec)
  377. })
  378. })
  379. }, [view, mode])
  380. useEffect(() => {
  381. settingsRef.current.syntaxValidation = syntaxValidation
  382. window.setTimeout(() => {
  383. view.dispatch(setSyntaxValidation(syntaxValidation))
  384. })
  385. }, [view, syntaxValidation])
  386. useEffect(() => {
  387. settingsRef.current.mathPreview = mathPreview
  388. window.setTimeout(() => {
  389. view.dispatch(setMathPreview(mathPreview))
  390. })
  391. }, [view, mathPreview])
  392. useEffect(() => {
  393. settingsRef.current.referencesSearchMode = referencesSearchMode
  394. }, [referencesSearchMode])
  395. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  396. // select and scroll to position on editor:gotoLine event (from synctex)
  397. useScopeEventListener(
  398. 'editor:gotoLine',
  399. useCallback(
  400. (_event: any, options: GotoLineOptions) => {
  401. setCursorLineAndScroll(
  402. view,
  403. options.gotoLine,
  404. options.gotoColumn,
  405. options.selectText
  406. )
  407. if (options.syncToPdf) {
  408. emitSyncToPdf()
  409. }
  410. },
  411. [emitSyncToPdf, view]
  412. )
  413. )
  414. // select and scroll to position on editor:gotoOffset event (from review panel)
  415. useScopeEventListener(
  416. 'editor:gotoOffset',
  417. useCallback(
  418. (_event: any, options: GotoOffsetOptions) => {
  419. setCursorPositionAndScroll(view, options.gotoOffset)
  420. },
  421. [view]
  422. )
  423. )
  424. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  425. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  426. const handleCursorUpdate = useCallback(
  427. (event: CustomEvent) => {
  428. dispatchCursorUpdate(event.detail)
  429. },
  430. [dispatchCursorUpdate]
  431. )
  432. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  433. useEventListener('cursor:editor:update', handleCursorUpdate)
  434. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  435. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  436. const handleScrollUpdate = useCallback(
  437. (event: CustomEvent) => {
  438. dispatchScrollUpdate(event.detail)
  439. },
  440. [dispatchScrollUpdate]
  441. )
  442. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  443. useEventListener('scroll:editor:update', handleScrollUpdate)
  444. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  445. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  446. // but we don't want to display the compile log diagnostics from the previous compile.
  447. const enableCompileLogLinter =
  448. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  449. // store enableCompileLogLinter in a ref for use in useEffect
  450. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  451. useEffect(() => {
  452. enableCompileLogLinterRef.current = enableCompileLogLinter
  453. }, [enableCompileLogLinter])
  454. // enable/disable the compile log linter as appropriate
  455. useEffect(() => {
  456. window.setTimeout(() => {
  457. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  458. })
  459. }, [view, enableCompileLogLinter])
  460. // set the compile log annotations when they change
  461. useEffect(() => {
  462. if (currentDocument && logEntryAnnotations) {
  463. const annotations = logEntryAnnotations[currentDocument.doc_id]
  464. window.setTimeout(() => {
  465. view.dispatch(
  466. setAnnotations(view.state, annotations || []),
  467. // reconfigure the compile log lint source, so it runs once with the new data
  468. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  469. )
  470. })
  471. }
  472. }, [view, currentDocument, logEntryAnnotations])
  473. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  474. cursorHighlights: [],
  475. })
  476. useEffect(() => {
  477. if (onlineUserCursorHighlights && currentDocument) {
  478. const items = onlineUserCursorHighlights[currentDocument.doc_id]
  479. highlightsRef.current.cursorHighlights = items
  480. window.setTimeout(() => {
  481. view.dispatch(setCursorHighlights(items))
  482. })
  483. }
  484. }, [view, onlineUserCursorHighlights, currentDocument])
  485. useEventListener(
  486. 'editor:focus',
  487. useCallback(() => {
  488. view.focus()
  489. }, [view])
  490. )
  491. }
  492. export default useCodeMirrorScope