use-codemirror-scope.ts 19 KB

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