use-codemirror-scope.ts 18 KB

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