use-codemirror-scope.ts 15 KB

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