use-codemirror-scope.ts 20 KB

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