use-codemirror-scope.ts 15 KB

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