use-codemirror-scope.ts 18 KB

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