use-codemirror-scope.ts 17 KB

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