use-codemirror-scope.ts 15 KB

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