use-codemirror-scope.ts 15 KB

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