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 {
  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. view.dispatch(setSpellCheckLanguage(spellingRef.current))
  202. }, [view, spellCheckLanguage, hunspellManager])
  203. const projectFeaturesRef = useRef(projectFeatures)
  204. // listen to doc:after-opened, and focus the editor if it's not a new doc
  205. useEffect(() => {
  206. const listener: EventListener = event => {
  207. const { isNewDoc } = (event as CustomEvent<{ isNewDoc: boolean }>).detail
  208. if (!isNewDoc) {
  209. window.setTimeout(() => {
  210. view.focus()
  211. }, 0)
  212. }
  213. }
  214. window.addEventListener('doc:after-opened', listener)
  215. return () => window.removeEventListener('doc:after-opened', listener)
  216. }, [view])
  217. // set the project metadata, mostly for use in autocomplete
  218. // TODO: read this data from the scope?
  219. const metadataRef = useRef({
  220. ...metadata,
  221. referenceKeys,
  222. fileTreeData,
  223. })
  224. // listen to project metadata (commands, labels and package names) updates
  225. useEffect(() => {
  226. metadataRef.current = { ...metadataRef.current, ...metadata }
  227. window.setTimeout(() => {
  228. view.dispatch(setMetadata(metadataRef.current))
  229. })
  230. }, [view, metadata])
  231. // listen to project reference keys updates
  232. useEffect(() => {
  233. metadataRef.current.referenceKeys = referenceKeys
  234. window.setTimeout(() => {
  235. view.dispatch(setMetadata(metadataRef.current))
  236. })
  237. }, [view, referenceKeys])
  238. // listen to project root folder updates
  239. useEffect(() => {
  240. if (fileTreeData) {
  241. metadataRef.current.fileTreeData = fileTreeData
  242. window.setTimeout(() => {
  243. view.dispatch(setMetadata(metadataRef.current))
  244. })
  245. }
  246. }, [view, fileTreeData])
  247. const editableRef = useRef(permissions.write)
  248. const { previewByPath } = useFileTreePathContext()
  249. const showVisual = visual && isValidTexFile(docName)
  250. const visualRef = useRef({
  251. previewByPath,
  252. visual: showVisual,
  253. })
  254. const handleError = useErrorHandler()
  255. const handleException = useCallback((exception: any) => {
  256. captureException(exception, {
  257. tags: {
  258. handler: 'cm6-exception',
  259. // which editor mode is active ('visual' | 'code')
  260. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  261. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  262. ol_editor_keybindings: settingsRef.current.mode,
  263. // whether Writefull is present ('extension' | 'integration' | 'none')
  264. ol_extensions_writefull: window.writefull?.type ?? 'none',
  265. // whether Grammarly is present
  266. ol_extensions_grammarly: grammarlyExtensionPresent(),
  267. },
  268. })
  269. }, [])
  270. // create a new state when currentDoc changes
  271. useEffect(() => {
  272. if (currentDoc) {
  273. debugConsole.log('creating new editor state')
  274. const state = EditorState.create({
  275. doc: currentDoc.getSnapshot(),
  276. extensions: createExtensions({
  277. currentDoc: {
  278. ...currentDocRef.current,
  279. currentDoc,
  280. },
  281. docName: docNameRef.current,
  282. theme: themeRef.current,
  283. metadata: metadataRef.current,
  284. settings: settingsRef.current,
  285. phrases: phrasesRef.current,
  286. spelling: spellingRef.current,
  287. visual: visualRef.current,
  288. projectFeatures: projectFeaturesRef.current,
  289. changeManager: createChangeManager(view, currentDoc),
  290. handleError,
  291. handleException,
  292. }),
  293. })
  294. view.setState(state)
  295. // synchronous config
  296. view.dispatch(
  297. restoreCursorPosition(state.doc, currentDoc.doc_id),
  298. setEditable(editableRef.current),
  299. setOptionsTheme(themeRef.current)
  300. )
  301. // asynchronous config
  302. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  303. view.dispatch(spec)
  304. })
  305. setKeybindings(settingsRef.current.mode).then(spec => {
  306. view.dispatch(spec)
  307. })
  308. if (!visualRef.current.visual) {
  309. window.setTimeout(() => {
  310. view.dispatch(restoreScrollPosition())
  311. view.focus()
  312. })
  313. }
  314. }
  315. // IMPORTANT: This effect must not depend on anything variable apart from currentDoc,
  316. // as the editor state is recreated when the effect runs.
  317. }, [view, currentDoc, handleError, handleException])
  318. useEffect(() => {
  319. if (docName) {
  320. docNameRef.current = docName
  321. view.dispatch(
  322. setDocName(docNameRef.current),
  323. setLanguage(
  324. docNameRef.current,
  325. metadataRef.current,
  326. settingsRef.current.syntaxValidation
  327. )
  328. )
  329. }
  330. }, [view, docName])
  331. useEffect(() => {
  332. visualRef.current.visual = showVisual
  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. }, [view, showVisual])
  340. useEffect(() => {
  341. visualRef.current.previewByPath = previewByPath
  342. view.dispatch(setVisual(visualRef.current))
  343. }, [view, previewByPath])
  344. useEffect(() => {
  345. editableRef.current = permissions.write
  346. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  347. }, [view, permissions.write])
  348. useEffect(() => {
  349. phrasesRef.current = phrases
  350. view.dispatch(setPhrases(phrases))
  351. }, [view, phrases])
  352. // listen to editor settings updates
  353. useEffect(() => {
  354. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  355. view.dispatch(setAutoPair(autoPairDelimiters))
  356. }, [view, autoPairDelimiters])
  357. useEffect(() => {
  358. settingsRef.current.autoComplete = autoComplete
  359. view.dispatch(
  360. setAutoComplete({
  361. enabled: autoComplete,
  362. projectFeatures: projectFeaturesRef.current,
  363. })
  364. )
  365. }, [view, autoComplete])
  366. useEffect(() => {
  367. settingsRef.current.mode = mode
  368. setKeybindings(mode).then(spec => {
  369. view.dispatch(spec)
  370. })
  371. }, [view, mode])
  372. useEffect(() => {
  373. settingsRef.current.syntaxValidation = syntaxValidation
  374. view.dispatch(setSyntaxValidation(syntaxValidation))
  375. }, [view, syntaxValidation])
  376. useEffect(() => {
  377. settingsRef.current.mathPreview = mathPreview
  378. view.dispatch(setMathPreview(mathPreview))
  379. }, [view, mathPreview])
  380. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  381. const handleGoToLine = useCallback(
  382. (event, lineNumber, columnNumber, syncToPdf) => {
  383. setCursorLineAndScroll(view, lineNumber, columnNumber)
  384. if (syncToPdf) {
  385. emitSyncToPdf()
  386. }
  387. },
  388. [emitSyncToPdf, view]
  389. )
  390. // select and scroll to position on editor:gotoLine event (from synctex)
  391. useScopeEventListener('editor:gotoLine', handleGoToLine)
  392. const handleGoToOffset = useCallback(
  393. (event, offset) => {
  394. setCursorPositionAndScroll(view, offset)
  395. },
  396. [view]
  397. )
  398. // select and scroll to position on editor:gotoOffset event (from review panel)
  399. useScopeEventListener('editor:gotoOffset', handleGoToOffset)
  400. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  401. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  402. const handleCursorUpdate = useCallback(
  403. (event: CustomEvent) => {
  404. dispatchCursorUpdate(event.detail)
  405. },
  406. [dispatchCursorUpdate]
  407. )
  408. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  409. useEventListener('cursor:editor:update', handleCursorUpdate)
  410. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  411. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  412. const handleScrollUpdate = useCallback(
  413. (event: CustomEvent) => {
  414. dispatchScrollUpdate(event.detail)
  415. },
  416. [dispatchScrollUpdate]
  417. )
  418. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  419. useEventListener('scroll:editor:update', handleScrollUpdate)
  420. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  421. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  422. // but we don't want to display the compile log diagnostics from the previous compile.
  423. const enableCompileLogLinter =
  424. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  425. // store enableCompileLogLinter in a ref for use in useEffect
  426. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  427. useEffect(() => {
  428. enableCompileLogLinterRef.current = enableCompileLogLinter
  429. }, [enableCompileLogLinter])
  430. // enable/disable the compile log linter as appropriate
  431. useEffect(() => {
  432. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  433. window.setTimeout(() => {
  434. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  435. }, 0)
  436. }, [view, enableCompileLogLinter])
  437. // set the compile log annotations when they change
  438. useEffect(() => {
  439. if (currentDoc && logEntryAnnotations) {
  440. const annotations = logEntryAnnotations[currentDoc.doc_id]
  441. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  442. window.setTimeout(() => {
  443. view.dispatch(
  444. setAnnotations(view.state, annotations || []),
  445. // reconfigure the compile log lint source, so it runs once with the new data
  446. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  447. )
  448. })
  449. }
  450. }, [view, currentDoc, logEntryAnnotations])
  451. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  452. cursorHighlights: [],
  453. })
  454. useEffect(() => {
  455. if (cursorHighlights && currentDoc) {
  456. const items = cursorHighlights[currentDoc.doc_id]
  457. highlightsRef.current.cursorHighlights = items
  458. window.setTimeout(() => {
  459. view.dispatch(setCursorHighlights(items))
  460. })
  461. }
  462. }, [view, cursorHighlights, currentDoc])
  463. const handleAddLearnedWords = useCallback(
  464. (event: CustomEvent<string>) => {
  465. // If the word addition is from adding the word to the dictionary via the
  466. // editor, there will be a transaction running now so wait for that to
  467. // finish before starting a new one
  468. window.setTimeout(() => {
  469. view.dispatch(addLearnedWord(spellCheckLanguage, event.detail))
  470. }, 0)
  471. },
  472. [spellCheckLanguage, view]
  473. )
  474. useEventListener('learnedWords:add', handleAddLearnedWords)
  475. const handleRemoveLearnedWords = useCallback(
  476. (event: CustomEvent<string>) => {
  477. view.dispatch(removeLearnedWord(spellCheckLanguage, event.detail))
  478. },
  479. [spellCheckLanguage, view]
  480. )
  481. useEventListener('learnedWords:remove', handleRemoveLearnedWords)
  482. const handleResetLearnedWords = useCallback(() => {
  483. view.dispatch(resetLearnedWords())
  484. }, [view])
  485. useEventListener('learnedWords:reset', handleResetLearnedWords)
  486. useEffect(() => {
  487. view.dispatch(reviewPanelToggled())
  488. }, [reviewPanelOpen, miniReviewPanelVisible, view])
  489. }
  490. export default useCodeMirrorScope