use-codemirror-scope.ts 15 KB

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