use-codemirror-scope.ts 16 KB

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