use-codemirror-scope.ts 18 KB

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