use-codemirror-scope.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import { useCallback, useEffect, useRef } from 'react'
  2. import { EditorState } from '@codemirror/state'
  3. import useScopeEventEmitter from '../../../shared/hooks/use-scope-event-emitter'
  4. import useEventListener from '../../../shared/hooks/use-event-listener'
  5. import useScopeEventListener from '../../../shared/hooks/use-scope-event-listener'
  6. import { createExtensions } from '../extensions'
  7. import { setEditorTheme, setOptionsTheme } from '../extensions/theme'
  8. import {
  9. restoreCursorPosition,
  10. setCursorLineAndScroll,
  11. setCursorPositionAndScroll,
  12. } from '../extensions/cursor-position'
  13. import {
  14. setAnnotations,
  15. showCompileLogDiagnostics,
  16. } from '../extensions/annotations'
  17. import { useDetachCompileContext as useCompileContext } from '../../../shared/context/detach-compile-context'
  18. import { setCursorHighlights } from '../extensions/cursor-highlights'
  19. import {
  20. setLanguage,
  21. setMetadata,
  22. setSyntaxValidation,
  23. } from '../extensions/language'
  24. import { restoreScrollPosition } from '../extensions/scroll-position'
  25. import { setEditable } from '../extensions/editable'
  26. import { useFileTreeData } from '../../../shared/context/file-tree-data-context'
  27. import { setAutoPair } from '../extensions/auto-pair'
  28. import { setAutoComplete } from '../extensions/auto-complete'
  29. import { usePhrases } from './use-phrases'
  30. import { setPhrases } from '../extensions/phrases'
  31. import { setSpellCheckLanguage } from '../extensions/spelling'
  32. import { setKeybindings } from '../extensions/keybindings'
  33. import { Highlight } from '../../../../../types/highlight'
  34. import { EditorView } from '@codemirror/view'
  35. import { useErrorBoundary } from 'react-error-boundary'
  36. import { setVisual } from '../extensions/visual/visual'
  37. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  38. import { useUserSettingsContext } from '@/shared/context/user-settings-context'
  39. import { setDocName } from '@/features/source-editor/extensions/doc-name'
  40. import { captureException } from '@/infrastructure/error-reporter'
  41. import grammarlyExtensionPresent from '@/shared/utils/grammarly'
  42. import { debugConsole } from '@/utils/debugging'
  43. import { useMetadataContext } from '@/features/ide-react/context/metadata-context'
  44. import { useUserContext } from '@/shared/context/user-context'
  45. import { useReferencesContext } from '@/features/ide-react/context/references-context'
  46. import { setMathPreview } from '@/features/source-editor/extensions/math-preview'
  47. import { useRangesContext } from '@/features/review-panel/context/ranges-context'
  48. import { updateRanges } from '@/features/source-editor/extensions/ranges'
  49. import { useThreadsContext } from '@/features/review-panel/context/threads-context'
  50. import { useHunspell } from '@/features/source-editor/hooks/use-hunspell'
  51. import { Permissions } from '@/features/ide-react/types/permissions'
  52. import { GotoOffsetOptions } from '@/features/ide-react/context/editor-manager-context'
  53. import { GotoLineOptions } from '@/features/ide-react/types/goto-line-options'
  54. import { useOnlineUsersContext } from '@/features/ide-react/context/online-users-context'
  55. import { useEditorOpenDocContext } from '@/features/ide-react/context/editor-open-doc-context'
  56. import { useProjectContext } from '@/shared/context/project-context'
  57. import { usePermissionsContext } from '@/features/ide-react/context/permissions-context'
  58. import { useEditorPropertiesContext } from '@/features/ide-react/context/editor-properties-context'
  59. import { SearchQuery } from '@codemirror/search'
  60. import { beforeChangeDocEffect } from '@/features/source-editor/extensions/before-change-doc'
  61. import { useActiveOverallTheme } from '@/shared/hooks/use-active-overall-theme'
  62. import { useEditorSelectionContext } from '@/shared/context/editor-selection-context'
  63. import { useActiveEditorTheme } from '@/shared/hooks/use-active-editor-theme'
  64. import { isVisualEditorAvailable } from '../utils/visual-editor'
  65. function useCodeMirrorScope(view: EditorView) {
  66. const { fileTreeData } = useFileTreeData()
  67. const permissions: Permissions = usePermissionsContext()
  68. // set up scope listeners
  69. const { logEntryAnnotations, editedSinceCompileStarted, compiling } =
  70. useCompileContext()
  71. const { openDocName, currentDocument } = useEditorOpenDocContext()
  72. const metadata = useMetadataContext()
  73. const { id: userId } = useUserContext()
  74. const { userSettings } = useUserSettingsContext()
  75. const {
  76. fontFamily,
  77. fontSize,
  78. lineHeight,
  79. autoComplete,
  80. autoPairDelimiters,
  81. mode,
  82. syntaxValidation,
  83. mathPreview,
  84. referencesSearchMode,
  85. enableNewEditor,
  86. } = userSettings
  87. const activeOverallTheme = useActiveOverallTheme()
  88. const editorTheme = useActiveEditorTheme()
  89. const { onlineUserCursorHighlights } = useOnlineUsersContext()
  90. const { project, features: projectFeatures } = useProjectContext()
  91. let spellCheckLanguage = project?.spellCheckLanguage || ''
  92. // spell check is off when read-only
  93. if (!permissions.write && !permissions.trackedWrite) {
  94. spellCheckLanguage = ''
  95. }
  96. const hunspellManager = useHunspell(spellCheckLanguage)
  97. const { showVisual: visual, trackChanges } = useEditorPropertiesContext()
  98. const { referenceKeys, searchLocalReferences } = useReferencesContext()
  99. const { setEditorSelection } = useEditorSelectionContext()
  100. const ranges = useRangesContext()
  101. const threads = useThreadsContext()
  102. // build the translation phrases
  103. const phrases = usePhrases()
  104. const phrasesRef = useRef(phrases)
  105. // initialise the local state
  106. const themeRef = useRef({
  107. fontFamily,
  108. fontSize,
  109. lineHeight,
  110. activeOverallTheme,
  111. editorTheme,
  112. })
  113. useEffect(() => {
  114. themeRef.current = {
  115. fontFamily,
  116. fontSize,
  117. lineHeight,
  118. activeOverallTheme,
  119. editorTheme,
  120. }
  121. view.dispatch(
  122. setOptionsTheme({
  123. fontFamily,
  124. fontSize,
  125. lineHeight,
  126. activeOverallTheme,
  127. })
  128. )
  129. setEditorTheme(editorTheme).then(spec => {
  130. view.dispatch(spec)
  131. })
  132. }, [view, fontFamily, fontSize, lineHeight, activeOverallTheme, editorTheme])
  133. const settingsRef = useRef({
  134. autoComplete,
  135. autoPairDelimiters,
  136. mode,
  137. syntaxValidation,
  138. mathPreview,
  139. referencesSearchMode,
  140. enableNewEditor,
  141. })
  142. const currentDocRef = useRef({
  143. currentDocument,
  144. trackChanges,
  145. })
  146. useEffect(() => {
  147. if (currentDocument) {
  148. currentDocRef.current.currentDocument = currentDocument
  149. }
  150. }, [view, currentDocument])
  151. useEffect(() => {
  152. if (ranges && threads) {
  153. window.setTimeout(() => {
  154. view.dispatch(updateRanges({ ranges, threads }))
  155. })
  156. }
  157. }, [view, ranges, threads])
  158. const docNameRef = useRef(openDocName)
  159. useEffect(() => {
  160. currentDocRef.current.trackChanges = trackChanges
  161. if (currentDocument) {
  162. if (trackChanges) {
  163. currentDocument.setTrackChangesUserId(userId ?? 'anonymous')
  164. } else {
  165. currentDocument.setTrackChangesUserId(null)
  166. }
  167. }
  168. }, [userId, currentDocument, trackChanges])
  169. const spellingRef = useRef({
  170. spellCheckLanguage,
  171. hunspellManager,
  172. })
  173. useEffect(() => {
  174. spellingRef.current = {
  175. spellCheckLanguage,
  176. hunspellManager,
  177. }
  178. window.setTimeout(() => {
  179. view.dispatch(setSpellCheckLanguage(spellingRef.current))
  180. })
  181. }, [view, spellCheckLanguage, hunspellManager])
  182. const projectFeaturesRef = useRef(projectFeatures)
  183. // listen to doc:after-opened, and focus the editor if it's not a new doc
  184. useEffect(() => {
  185. const listener: EventListener = event => {
  186. const { isNewDoc } = (event as CustomEvent<{ isNewDoc: boolean }>).detail
  187. if (!isNewDoc) {
  188. window.setTimeout(() => {
  189. view.focus()
  190. }, 0)
  191. }
  192. }
  193. window.addEventListener('doc:after-opened', listener)
  194. return () => window.removeEventListener('doc:after-opened', listener)
  195. }, [view])
  196. // set the project metadata, mostly for use in autocomplete
  197. // TODO: read this data from the scope?
  198. const metadataRef = useRef({
  199. ...metadata,
  200. referenceKeys,
  201. searchLocalReferences,
  202. fileTreeData,
  203. })
  204. // listen to project metadata (commands, labels and package names) updates
  205. useEffect(() => {
  206. metadataRef.current = { ...metadataRef.current, ...metadata }
  207. window.setTimeout(() => {
  208. view.dispatch(setMetadata(metadataRef.current))
  209. })
  210. }, [view, metadata])
  211. // listen to project reference keys updates
  212. useEffect(() => {
  213. metadataRef.current.referenceKeys = referenceKeys
  214. window.setTimeout(() => {
  215. view.dispatch(setMetadata(metadataRef.current))
  216. })
  217. }, [view, referenceKeys])
  218. // listen to project reference search updates
  219. useEffect(() => {
  220. metadataRef.current.searchLocalReferences = searchLocalReferences
  221. window.setTimeout(() => {
  222. view.dispatch(setMetadata(metadataRef.current))
  223. })
  224. }, [view, searchLocalReferences])
  225. // listen to project root folder updates
  226. useEffect(() => {
  227. if (fileTreeData) {
  228. metadataRef.current.fileTreeData = fileTreeData
  229. window.setTimeout(() => {
  230. view.dispatch(setMetadata(metadataRef.current))
  231. })
  232. }
  233. }, [view, fileTreeData])
  234. const editableRef = useRef(permissions.write || permissions.trackedWrite)
  235. const { previewByPath } = useFileTreePathContext()
  236. const showVisual =
  237. visual && !!openDocName && isVisualEditorAvailable(openDocName)
  238. const visualRef = useRef({
  239. previewByPath,
  240. visual: showVisual,
  241. })
  242. // Persist the search query in this hook when the document changes by keeping
  243. // a reference to the search query in sync with the editor state
  244. const searchQueryRef = useRef<SearchQuery | null>(null)
  245. useEventListener(
  246. 'search-panel-before-doc-change',
  247. useCallback((event: CustomEvent) => {
  248. searchQueryRef.current = event.detail
  249. }, [])
  250. )
  251. const { showBoundary } = useErrorBoundary()
  252. const handleException = useCallback((exception: any) => {
  253. captureException(exception, {
  254. tags: {
  255. handler: 'cm6-exception',
  256. // which editor mode is active ('visual' | 'code')
  257. ol_editor_mode: visualRef.current.visual ? 'visual' : 'code',
  258. // which editor keybindings are active ('default' | 'vim' | 'emacs')
  259. ol_editor_keybindings: settingsRef.current.mode,
  260. // whether Writefull is present ('extension' | 'integration' | 'none')
  261. ol_extensions_writefull: window.writefull ? 'integration' : 'none',
  262. // whether Grammarly is present
  263. ol_extensions_grammarly: grammarlyExtensionPresent(),
  264. },
  265. })
  266. }, [])
  267. // create a new state when currentDocument changes
  268. useEffect(() => {
  269. if (currentDocument) {
  270. debugConsole.log('creating new editor state')
  271. // Warn any interested extension that the document is about to change,
  272. // allowing it to perform any necessary actions before creating the new
  273. // state. destroy() is too late because the new state is already created
  274. view.dispatch({
  275. effects: beforeChangeDocEffect.of(null),
  276. })
  277. const state = EditorState.create({
  278. doc: currentDocument.getSnapshot(),
  279. extensions: createExtensions({
  280. currentDoc: {
  281. ...currentDocRef.current,
  282. currentDoc: currentDocument,
  283. },
  284. docName: docNameRef.current,
  285. theme: themeRef.current,
  286. metadata: metadataRef.current,
  287. settings: settingsRef.current,
  288. phrases: phrasesRef.current,
  289. spelling: spellingRef.current,
  290. visual: visualRef.current,
  291. projectFeatures: projectFeaturesRef.current,
  292. initialSearchQuery: searchQueryRef.current,
  293. showBoundary,
  294. handleException,
  295. setEditorSelection,
  296. }),
  297. })
  298. view.setState(state)
  299. // synchronous config
  300. view.dispatch(
  301. restoreCursorPosition(state.doc, currentDocument.doc_id),
  302. setEditable(editableRef.current),
  303. setOptionsTheme(themeRef.current)
  304. )
  305. // asynchronous config
  306. setEditorTheme(themeRef.current.editorTheme).then(spec => {
  307. view.dispatch(spec)
  308. })
  309. setKeybindings(settingsRef.current.mode).then(spec => {
  310. view.dispatch(spec)
  311. })
  312. if (!visualRef.current.visual) {
  313. window.setTimeout(() => {
  314. view.dispatch(restoreScrollPosition())
  315. view.focus()
  316. })
  317. }
  318. }
  319. // IMPORTANT: This effect must not depend on anything variable apart from currentDocument,
  320. // as the editor state is recreated when the effect runs.
  321. }, [view, currentDocument, showBoundary, handleException, setEditorSelection])
  322. useEffect(() => {
  323. if (openDocName) {
  324. docNameRef.current = openDocName
  325. window.setTimeout(() => {
  326. view.dispatch(
  327. setDocName(openDocName),
  328. setLanguage(
  329. openDocName,
  330. metadataRef.current,
  331. settingsRef.current.syntaxValidation
  332. )
  333. )
  334. })
  335. }
  336. }, [view, openDocName])
  337. useEffect(() => {
  338. visualRef.current.visual = showVisual
  339. window.setTimeout(() => {
  340. view.dispatch(setVisual(visualRef.current))
  341. view.dispatch({
  342. effects: EditorView.scrollIntoView(view.state.selection.main.head),
  343. })
  344. // clear performance measures and marks when switching between Source and Rich Text
  345. window.dispatchEvent(new Event('editor:visual-switch'))
  346. })
  347. }, [view, showVisual])
  348. useEffect(() => {
  349. visualRef.current.previewByPath = previewByPath
  350. window.setTimeout(() => {
  351. view.dispatch(setVisual(visualRef.current))
  352. })
  353. }, [view, previewByPath])
  354. useEffect(() => {
  355. editableRef.current = permissions.write || permissions.trackedWrite
  356. window.setTimeout(() => {
  357. view.dispatch(setEditable(editableRef.current)) // the editor needs to be locked when there's a problem saving data
  358. })
  359. }, [view, permissions.write, permissions.trackedWrite])
  360. useEffect(() => {
  361. phrasesRef.current = phrases
  362. window.setTimeout(() => {
  363. view.dispatch(setPhrases(phrases))
  364. })
  365. }, [view, phrases])
  366. // listen to editor settings updates
  367. useEffect(() => {
  368. settingsRef.current.autoPairDelimiters = autoPairDelimiters
  369. window.setTimeout(() => {
  370. view.dispatch(setAutoPair(autoPairDelimiters))
  371. })
  372. }, [view, autoPairDelimiters])
  373. useEffect(() => {
  374. settingsRef.current.autoComplete = autoComplete
  375. window.setTimeout(() => {
  376. view.dispatch(
  377. setAutoComplete({
  378. enabled: autoComplete,
  379. projectFeatures: projectFeaturesRef.current,
  380. referencesSearchMode: settingsRef.current.referencesSearchMode,
  381. })
  382. )
  383. })
  384. }, [view, autoComplete])
  385. useEffect(() => {
  386. settingsRef.current.mode = mode
  387. setKeybindings(mode).then(spec => {
  388. window.setTimeout(() => {
  389. view.dispatch(spec)
  390. })
  391. })
  392. }, [view, mode])
  393. useEffect(() => {
  394. settingsRef.current.syntaxValidation = syntaxValidation
  395. window.setTimeout(() => {
  396. view.dispatch(setSyntaxValidation(syntaxValidation))
  397. })
  398. }, [view, syntaxValidation])
  399. useEffect(() => {
  400. settingsRef.current.mathPreview = mathPreview
  401. window.setTimeout(() => {
  402. view.dispatch(setMathPreview(mathPreview))
  403. })
  404. }, [view, mathPreview])
  405. useEffect(() => {
  406. settingsRef.current.referencesSearchMode = referencesSearchMode
  407. }, [referencesSearchMode])
  408. const emitSyncToPdf = useScopeEventEmitter('cursor:editor:syncToPdf')
  409. // select and scroll to position on editor:gotoLine event (from synctex)
  410. useScopeEventListener(
  411. 'editor:gotoLine',
  412. useCallback(
  413. (_event: any, options: GotoLineOptions) => {
  414. setCursorLineAndScroll(
  415. view,
  416. options.gotoLine,
  417. options.gotoColumn,
  418. options.selectText
  419. )
  420. if (options.syncToPdf) {
  421. emitSyncToPdf()
  422. }
  423. },
  424. [emitSyncToPdf, view]
  425. )
  426. )
  427. // select and scroll to position on editor:gotoOffset event (from review panel)
  428. useScopeEventListener(
  429. 'editor:gotoOffset',
  430. useCallback(
  431. (_event: any, options: GotoOffsetOptions) => {
  432. setCursorPositionAndScroll(view, options.gotoOffset)
  433. },
  434. [view]
  435. )
  436. )
  437. // dispatch 'cursor:editor:update' to Angular scope (for synctex and realtime)
  438. const dispatchCursorUpdate = useScopeEventEmitter('cursor:editor:update')
  439. const handleCursorUpdate = useCallback(
  440. (event: CustomEvent) => {
  441. dispatchCursorUpdate(event.detail)
  442. },
  443. [dispatchCursorUpdate]
  444. )
  445. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  446. useEventListener('cursor:editor:update', handleCursorUpdate)
  447. // dispatch 'cursor:editor:update' to Angular scope (for outline)
  448. const dispatchScrollUpdate = useScopeEventEmitter('scroll:editor:update')
  449. const handleScrollUpdate = useCallback(
  450. (event: CustomEvent) => {
  451. dispatchScrollUpdate(event.detail)
  452. },
  453. [dispatchScrollUpdate]
  454. )
  455. // listen for 'cursor:editor:update' events from CodeMirror, and dispatch them to Angular
  456. useEventListener('scroll:editor:update', handleScrollUpdate)
  457. // enable the compile log linter a) when "Code Check" is off, b) when the project hasn't changed and isn't compiling.
  458. // the project "changed at" date is reset at the start of the compile, i.e. "the project hasn't changed",
  459. // but we don't want to display the compile log diagnostics from the previous compile.
  460. const enableCompileLogLinter =
  461. !syntaxValidation || (!editedSinceCompileStarted && !compiling)
  462. // store enableCompileLogLinter in a ref for use in useEffect
  463. const enableCompileLogLinterRef = useRef(enableCompileLogLinter)
  464. useEffect(() => {
  465. enableCompileLogLinterRef.current = enableCompileLogLinter
  466. }, [enableCompileLogLinter])
  467. // enable/disable the compile log linter as appropriate
  468. useEffect(() => {
  469. window.setTimeout(() => {
  470. view.dispatch(showCompileLogDiagnostics(enableCompileLogLinter))
  471. })
  472. }, [view, enableCompileLogLinter])
  473. // set the compile log annotations when they change
  474. useEffect(() => {
  475. if (currentDocument && logEntryAnnotations) {
  476. const annotations = logEntryAnnotations[currentDocument.doc_id]
  477. window.setTimeout(() => {
  478. view.dispatch(
  479. setAnnotations(view.state, annotations || []),
  480. // reconfigure the compile log lint source, so it runs once with the new data
  481. showCompileLogDiagnostics(enableCompileLogLinterRef.current)
  482. )
  483. })
  484. }
  485. }, [view, currentDocument, logEntryAnnotations])
  486. const highlightsRef = useRef<{ cursorHighlights: Highlight[] }>({
  487. cursorHighlights: [],
  488. })
  489. useEffect(() => {
  490. if (onlineUserCursorHighlights && currentDocument) {
  491. const items = onlineUserCursorHighlights[currentDocument.doc_id]
  492. highlightsRef.current.cursorHighlights = items
  493. window.setTimeout(() => {
  494. view.dispatch(setCursorHighlights(items))
  495. })
  496. }
  497. }, [view, onlineUserCursorHighlights, currentDocument])
  498. useEventListener(
  499. 'editor:focus',
  500. useCallback(() => {
  501. view.focus()
  502. }, [view])
  503. )
  504. }
  505. export default useCodeMirrorScope