use-codemirror-scope.ts 18 KB

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