use-codemirror-scope.ts 15 KB

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