use-codemirror-scope.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 getMeta from '../../../utils/meta'
  48. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  49. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  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 { userSettings } = useUserSettingsContext()
  62. const {
  63. fontFamily,
  64. fontSize,
  65. lineHeight,
  66. overallTheme,
  67. autoComplete,
  68. editorTheme,
  69. autoPairDelimiters,
  70. mode,
  71. syntaxValidation,
  72. } = userSettings
  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 { previewByPath } = useFileTreePathContext()
  213. const visualRef = useRef({
  214. previewByPath,
  215. visual,
  216. })
  217. const handleError = useErrorHandler()
  218. // create a new state when currentDoc changes
  219. useEffect(() => {
  220. if (currentDoc) {
  221. const state = EditorState.create({
  222. doc: currentDoc.getSnapshot(),
  223. extensions: createExtensions({
  224. currentDoc: {
  225. ...currentDocRef.current,
  226. currentDoc,
  227. },
  228. theme: themeRef.current,
  229. metadata: metadataRef.current,
  230. settings: settingsRef.current,
  231. phrases: phrasesRef.current,
  232. spelling: spellingRef.current,
  233. visual: visualRef.current,
  234. changeManager: createChangeManager(view, currentDoc),
  235. handleError,
  236. reactReviewPanel,
  237. }),
  238. })
  239. view.setState(state)
  240. // synchronous config
  241. view.dispatch(
  242. restoreCursorPosition(state.doc, currentDoc.doc_id),
  243. setEditable(editableRef.current),
  244. setOptionsTheme(themeRef.current)
  245. )
  246. // asynchronous config
  247. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  248. view.dispatch(spec)
  249. })
  250. setKeybindings(settingsRef.current.mode).then(spec => {
  251. view.dispatch(spec)
  252. })
  253. if (!visualRef.current.visual) {
  254. window.setTimeout(() => {
  255. view.dispatch(restoreScrollPosition())
  256. view.focus()
  257. })
  258. }
  259. }
  260. // IMPORTANT: This effect must not depend on anything variable apart from currentDoc,
  261. // as the editor state is recreated when the effect runs.
  262. }, [view, currentDoc, handleError, reactReviewPanel])
  263. useEffect(() => {
  264. visualRef.current.visual = visual
  265. view.dispatch(setVisual(visualRef.current))
  266. view.dispatch({
  267. effects: EditorView.scrollIntoView(view.state.selection.main.head),
  268. })
  269. // clear performance measures and marks when switching between Source and Rich Text
  270. window.dispatchEvent(new Event('editor:visual-switch'))
  271. }, [view, visual])
  272. useEffect(() => {
  273. visualRef.current.previewByPath = previewByPath
  274. view.dispatch(setVisual(visualRef.current))
  275. }, [view, previewByPath])
  276. useEffect(() => {
  277. editableRef.current = permissionsLevel !== 'readOnly'
  278. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  279. }, [view, permissionsLevel])
  280. useEffect(() => {
  281. phrasesRef.current = phrases
  282. view.dispatch(setPhrases(phrases))
  283. }, [view, phrases])
  284. // listen to editor settings updates
  285. useEffect(() => {
  286. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  287. view.dispatch(setAutoPair(autoPairDelimiters))
  288. }, [view, autoPairDelimiters])
  289. useEffect(() => {
  290. settingsRef.current.autoComplete = autoComplete
  291. view.dispatch(setAutoComplete(autoComplete))
  292. }, [view, autoComplete])
  293. useEffect(() => {
  294. settingsRef.current.mode = mode
  295. setKeybindings(mode).then(spec => {
  296. view.dispatch(spec)
  297. })
  298. }, [view, mode])
  299. useEffect(() => {
  300. settingsRef.current.syntaxValidation = syntaxValidation
  301. view.dispatch(setSyntaxValidation(syntaxValidation))
  302. }, [view, syntaxValidation])
  303. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  304. const handleGoToLine = useCallback(
  305. (event, lineNumber, columnNumber, syncToPdf) => {
  306. setCursorLineAndScroll(view, lineNumber, columnNumber)
  307. if (syncToPdf) {
  308. emitSyncToPdf()
  309. }
  310. },
  311. [emitSyncToPdf, view]
  312. )
  313. // select and scroll to position on editor:gotoLine event (from synctex)
  314. useScopeEventListener('editor:gotoLine', handleGoToLine)
  315. const handleGoToOffset = useCallback(
  316. (event, offset) => {
  317. setCursorPositionAndScroll(view, offset)
  318. },
  319. [view]
  320. )
  321. // select and scroll to position on editor:gotoOffset event (from review panel)
  322. useScopeEventListener('editor:gotoOffset', handleGoToOffset)
  323. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  324. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  325. const handleCursorUpdate = useCallback(
  326. (event: CustomEvent) => {
  327. dispatchCursorUpdate(event.detail)
  328. },
  329. [dispatchCursorUpdate]
  330. )
  331. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  332. useEventListener('cursor:editor:update', handleCursorUpdate)
  333. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  334. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  335. const handleScrollUpdate = useCallback(
  336. (event: CustomEvent) => {
  337. dispatchScrollUpdate(event.detail)
  338. },
  339. [dispatchScrollUpdate]
  340. )
  341. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  342. useEventListener('scroll:editor:update', handleScrollUpdate)
  343. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  344. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  345. // but we don't want to display the compile log diagnostics from the previous compile.
  346. const enableCompileLogLinter =
  347. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  348. // store enableCompileLogLinter in a ref for use in useEffect
  349. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  350. useEffect(() => {
  351. enableCompileLogLinterRef.current = enableCompileLogLinter
  352. }, [enableCompileLogLinter])
  353. // enable/disable the compile log linter as appropriate
  354. useEffect(() => {
  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(showCompileLogDiagnostics(enableCompileLogLinter))
  358. }, 0)
  359. }, [view, enableCompileLogLinter])
  360. // set the compile log annotations when they change
  361. useEffect(() => {
  362. if (currentDoc && logEntryAnnotations) {
  363. const annotations = logEntryAnnotations[currentDoc.doc_id]
  364. // dispatch in a timeout, so the dispatch isn't in the same cycle as the edit which caused it
  365. window.setTimeout(() => {
  366. view.dispatch(
  367. setAnnotations(view.state.doc, annotations || []),
  368. // reconfigure the compile log lint source, so it runs once with the new data
  369. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  370. )
  371. })
  372. }
  373. }, [view, currentDoc, logEntryAnnotations])
  374. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  375. cursorHighlights: [],
  376. })
  377. useEffect(() => {
  378. if (cursorHighlights && currentDoc) {
  379. const items = cursorHighlights[currentDoc.doc_id]
  380. highlightsRef.current.cursorHighlights = items
  381. window.setTimeout(() => {
  382. view.dispatch(setCursorHighlights(items))
  383. })
  384. }
  385. }, [view, cursorHighlights, currentDoc])
  386. const handleAddLearnedWords = useCallback(
  387. (event: CustomEvent<string>) => {
  388. // If the word addition is from adding the word to the dictionary via the
  389. // editor, there will be a transaction running now so wait for that to
  390. // finish before starting a new one
  391. window.setTimeout(() => {
  392. view.dispatch(addLearnedWord(spellCheckLanguage, event.detail))
  393. }, 0)
  394. },
  395. [spellCheckLanguage, view]
  396. )
  397. useEventListener('learnedWords:add', handleAddLearnedWords)
  398. const handleRemoveLearnedWords = useCallback(
  399. (event: CustomEvent<string>) => {
  400. view.dispatch(removeLearnedWord(spellCheckLanguage, event.detail))
  401. },
  402. [spellCheckLanguage, view]
  403. )
  404. useEventListener('learnedWords:remove', handleRemoveLearnedWords)
  405. const handleResetLearnedWords = useCallback(() => {
  406. view.dispatch(resetLearnedWords())
  407. }, [view])
  408. useEventListener('learnedWords:reset', handleResetLearnedWords)
  409. }
  410. export default useCodeMirrorScope
  411. const scheduleFocus = (view: EditorView) => {
  412. window.setTimeout(() => {
  413. view.focus()
  414. }, 0)
  415. }