use-codemirror-scope.ts 15 KB

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