use-codemirror-scope.ts 17 KB

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