use-codemirror-scope.ts 16 KB

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