use-codemirror-scope.ts 20 KB

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