use-codemirror-scope.ts 17 KB

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