use-codemirror-scope.ts 18 KB

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