use-codemirror-scope.ts 19 KB

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