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. 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. import getMeta from '../../../utils/meta'
  51. function useCodeMirrorScope(view: EditorView) {
  52. const ide = useIdeContext()
  53. const { fileTreeData } = useFileTreeData()
  54. const { permissionsLevel } = useEditorContext()
  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 [fontFamily] = useScopeValue<FontFamily>('settings.fontFamily')
  63. const [fontSize] = useScopeValue<number>('settings.fontSize')
  64. const [lineHeight] = useScopeValue<LineHeight>('settings.lineHeight')
  65. const [overallTheme] = useScopeValue<OverallTheme>('settings.overallTheme')
  66. const [autoComplete] = useScopeValue<boolean>('settings.autoComplete')
  67. const [editorTheme] = useScopeValue<string>('settings.editorTheme')
  68. const [autoPairDelimiters] = useScopeValue<boolean>(
  69. 'settings.autoPairDelimiters'
  70. )
  71. const [mode] = useScopeValue<string>('settings.mode')
  72. const [syntaxValidation] = useScopeValue<boolean>('settings.syntaxValidation')
  73. const [cursorHighlights] = useScopeValue<Record<string, Highlight[]>>(
  74. 'onlineUserCursorHighlights'
  75. )
  76. const [spellCheckLanguage] = useScopeValue<string>(
  77. 'project.spellCheckLanguage'
  78. )
  79. const [visual] = useScopeValue<boolean>('editor.showVisual')
  80. const reactReviewPanel: boolean = getMeta('ol-isReviewPanelReact')
  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. window.dispatchEvent(
  151. new CustomEvent('editor:event', {
  152. detail: {
  153. type: 'line-height',
  154. payload: lineHeights[lineHeight] * fontSize,
  155. },
  156. })
  157. )
  158. }
  159. }, [lineHeight, fontSize])
  160. const spellingRef = useRef({
  161. spellCheckLanguage,
  162. })
  163. useEffect(() => {
  164. spellingRef.current = {
  165. spellCheckLanguage,
  166. }
  167. view.dispatch(setSpelling(spellingRef.current))
  168. }, [view, spellCheckLanguage])
  169. // listen to doc:after-opened, and focus the editor
  170. useEffect(() => {
  171. const listener = () => {
  172. scheduleFocus(view)
  173. }
  174. window.addEventListener('doc:after-opened', listener)
  175. return () => window.removeEventListener('doc:after-opened', listener)
  176. }, [view])
  177. // set the project metadata, mostly for use in autocomplete
  178. // TODO: read this data from the scope?
  179. const metadataRef = useRef({
  180. documents: ide.metadataManager.metadata.state.documents,
  181. references: references.keys,
  182. fileTreeData,
  183. })
  184. // listen to project metadata (docs + packages) updates
  185. useEffect(() => {
  186. const listener = (event: Event) => {
  187. metadataRef.current.documents = (
  188. event as CustomEvent<Record<string, any>>
  189. ).detail
  190. view.dispatch(setMetadata(metadataRef.current))
  191. }
  192. window.addEventListener('project:metadata', listener)
  193. return () => window.removeEventListener('project:metadata', listener)
  194. }, [view])
  195. // listen to project reference keys updates
  196. useEffect(() => {
  197. const listener = (event: Event) => {
  198. metadataRef.current.references = (event as CustomEvent<string[]>).detail
  199. view.dispatch(setMetadata(metadataRef.current))
  200. }
  201. window.addEventListener('project:references', listener)
  202. return () => window.removeEventListener('project:references', listener)
  203. }, [view])
  204. // listen to project root folder updates
  205. useEffect(() => {
  206. if (fileTreeData) {
  207. metadataRef.current.fileTreeData = fileTreeData
  208. view.dispatch(setMetadata(metadataRef.current))
  209. }
  210. }, [view, fileTreeData])
  211. const editableRef = useRef(permissionsLevel !== 'readOnly')
  212. const visualRef = useRef({
  213. fileTreeManager: ide.fileTreeManager,
  214. visual,
  215. })
  216. const handleError = useErrorHandler()
  217. // create a new state when currentDoc changes
  218. useEffect(() => {
  219. if (currentDoc) {
  220. const state = EditorState.create({
  221. doc: currentDoc.getSnapshot(),
  222. extensions: createExtensions({
  223. currentDoc: {
  224. ...currentDocRef.current,
  225. currentDoc,
  226. },
  227. theme: themeRef.current,
  228. metadata: metadataRef.current,
  229. settings: settingsRef.current,
  230. phrases: phrasesRef.current,
  231. spelling: spellingRef.current,
  232. visual: visualRef.current,
  233. changeManager: createChangeManager(view, currentDoc),
  234. handleError,
  235. reactReviewPanel,
  236. }),
  237. })
  238. view.setState(state)
  239. // synchronous config
  240. view.dispatch(
  241. restoreCursorPosition(state.doc, currentDoc.doc_id),
  242. setEditable(editableRef.current),
  243. setOptionsTheme(themeRef.current)
  244. )
  245. // asynchronous config
  246. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  247. view.dispatch(spec)
  248. })
  249. setKeybindings(settingsRef.current.mode).then(spec => {
  250. view.dispatch(spec)
  251. })
  252. if (!visualRef.current.visual) {
  253. window.setTimeout(() => {
  254. view.dispatch(restoreScrollPosition())
  255. view.focus()
  256. })
  257. }
  258. }
  259. // IMPORTANT: This effect must not depend on anything variable apart from currentDoc,
  260. // as the editor state is recreated when the effect runs.
  261. }, [view, currentDoc, handleError, reactReviewPanel])
  262. useEffect(() => {
  263. visualRef.current.visual = visual
  264. view.dispatch(setVisual(visualRef.current))
  265. view.dispatch({
  266. effects: EditorView.scrollIntoView(view.state.selection.main.head),
  267. })
  268. // clear performance measures and marks when switching between Source and Rich Text
  269. window.dispatchEvent(new Event('editor:visual-switch'))
  270. }, [view, visual])
  271. useEffect(() => {
  272. editableRef.current = permissionsLevel !== 'readOnly'
  273. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  274. }, [view, permissionsLevel])
  275. useEffect(() => {
  276. phrasesRef.current = phrases
  277. view.dispatch(setPhrases(phrases))
  278. }, [view, phrases])
  279. // listen to editor settings updates
  280. useEffect(() => {
  281. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  282. view.dispatch(setAutoPair(autoPairDelimiters))
  283. }, [view, autoPairDelimiters])
  284. useEffect(() => {
  285. settingsRef.current.autoComplete = autoComplete
  286. view.dispatch(setAutoComplete(autoComplete))
  287. }, [view, autoComplete])
  288. useEffect(() => {
  289. settingsRef.current.mode = mode
  290. setKeybindings(mode).then(spec => {
  291. view.dispatch(spec)
  292. })
  293. }, [view, mode])
  294. useEffect(() => {
  295. settingsRef.current.syntaxValidation = syntaxValidation
  296. view.dispatch(setSyntaxValidation(syntaxValidation))
  297. }, [view, syntaxValidation])
  298. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  299. const handleGoToLine = useCallback(
  300. (event, lineNumber, columnNumber, syncToPdf) => {
  301. setCursorLineAndScroll(view, lineNumber, columnNumber)
  302. if (syncToPdf) {
  303. emitSyncToPdf()
  304. }
  305. },
  306. [emitSyncToPdf, view]
  307. )
  308. // select and scroll to position on editor:gotoLine event (from synctex)
  309. useScopeEventListener('editor:gotoLine', handleGoToLine)
  310. const handleGoToOffset = useCallback(
  311. (event, offset) => {
  312. setCursorPositionAndScroll(view, offset)
  313. },
  314. [view]
  315. )
  316. // select and scroll to position on editor:gotoOffset event (from review panel)
  317. useScopeEventListener('editor:gotoOffset', handleGoToOffset)
  318. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  319. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  320. const handleCursorUpdate = useCallback(
  321. (event: CustomEvent) => {
  322. dispatchCursorUpdate(event.detail)
  323. },
  324. [dispatchCursorUpdate]
  325. )
  326. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  327. useEventListener('cursor:editor:update', handleCursorUpdate)
  328. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  329. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  330. const handleScrollUpdate = useCallback(
  331. (event: CustomEvent) => {
  332. dispatchScrollUpdate(event.detail)
  333. },
  334. [dispatchScrollUpdate]
  335. )
  336. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  337. useEventListener('scroll:editor:update', handleScrollUpdate)
  338. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  339. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  340. // but we don't want to display the compile log diagnostics from the previous compile.
  341. const enableCompileLogLinter =
  342. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  343. // store enableCompileLogLinter in a ref for use in useEffect
  344. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  345. useEffect(() => {
  346. enableCompileLogLinterRef.current = enableCompileLogLinter
  347. }, [enableCompileLogLinter])
  348. // enable/disable the compile log linter as appropriate
  349. useEffect(() => {
  350. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  351. window.setTimeout(() => {
  352. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  353. }, 0)
  354. }, [view, enableCompileLogLinter])
  355. // set the compile log annotations when they change
  356. useEffect(() => {
  357. if (currentDoc && logEntryAnnotations) {
  358. const annotations = logEntryAnnotations[currentDoc.doc_id]
  359. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  360. window.setTimeout(() => {
  361. view.dispatch(
  362. setAnnotations(view.state.doc, annotations || []),
  363. // reconfigure the compile log lint source, so it runs once with the new data
  364. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  365. )
  366. })
  367. }
  368. }, [view, currentDoc, logEntryAnnotations])
  369. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  370. cursorHighlights: [],
  371. })
  372. useEffect(() => {
  373. if (cursorHighlights && currentDoc) {
  374. const items = cursorHighlights[currentDoc.doc_id]
  375. highlightsRef.current.cursorHighlights = items
  376. window.setTimeout(() => {
  377. view.dispatch(setCursorHighlights(items))
  378. })
  379. }
  380. }, [view, cursorHighlights, currentDoc])
  381. const handleAddLearnedWords = useCallback(
  382. (event: CustomEvent<string>) => {
  383. // If the word addition is from adding the word to the dictionary via the
  384. // editor, there will be a transaction running now so wait for that to
  385. // finish before starting a new one
  386. window.setTimeout(() => {
  387. view.dispatch(addLearnedWord(spellCheckLanguage, event.detail))
  388. }, 0)
  389. },
  390. [spellCheckLanguage, view]
  391. )
  392. useEventListener('learnedWords:add', handleAddLearnedWords)
  393. const handleRemoveLearnedWords = useCallback(
  394. (event: CustomEvent<string>) => {
  395. view.dispatch(removeLearnedWord(spellCheckLanguage, event.detail))
  396. },
  397. [spellCheckLanguage, view]
  398. )
  399. useEventListener('learnedWords:remove', handleRemoveLearnedWords)
  400. const handleResetLearnedWords = useCallback(() => {
  401. view.dispatch(resetLearnedWords())
  402. }, [view])
  403. useEventListener('learnedWords:reset', handleResetLearnedWords)
  404. }
  405. export default useCodeMirrorScope
  406. const scheduleFocus = (view: EditorView) => {
  407. window.setTimeout(() => {
  408. view.focus()
  409. }, 0)
  410. }