use-codemirror-scope.ts 15 KB

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