use-codemirror-scope.ts 17 KB

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