editor-manager-context.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. import {
  2. createContext,
  3. FC,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. } from 'react'
  11. import { sendMB } from '@/infrastructure/event-tracking'
  12. import useScopeValue from '@/shared/hooks/use-scope-value'
  13. import { useIdeContext } from '@/shared/context/ide-context'
  14. import { OpenDocuments } from '@/features/ide-react/editor/open-documents'
  15. import EditorWatchdogManager from '@/features/ide-react/connection/editor-watchdog-manager'
  16. import { useIdeReactContext } from '@/features/ide-react/context/ide-react-context'
  17. import { useConnectionContext } from '@/features/ide-react/context/connection-context'
  18. import { debugConsole } from '@/utils/debugging'
  19. import { DocumentContainer } from '@/features/ide-react/editor/document-container'
  20. import { useLayoutContext } from '@/shared/context/layout-context'
  21. import { GotoLineOptions } from '@/features/ide-react/types/goto-line-options'
  22. import { Doc } from '../../../../../types/doc'
  23. import { useFileTreeData } from '@/shared/context/file-tree-data-context'
  24. import { findDocEntityById } from '@/features/ide-react/util/find-doc-entity-by-id'
  25. import useScopeEventEmitter from '@/shared/hooks/use-scope-event-emitter'
  26. import { useModalsContext } from '@/features/ide-react/context/modals-context'
  27. import { useTranslation } from 'react-i18next'
  28. import customLocalStorage from '@/infrastructure/local-storage'
  29. import useEventListener from '@/shared/hooks/use-event-listener'
  30. import { EditorType } from '@/features/ide-react/editor/types/editor-type'
  31. import { DocId } from '../../../../../types/project-settings'
  32. import { Update } from '@/features/history/services/types/update'
  33. import { useDebugDiffTracker } from '../hooks/use-debug-diff-tracker'
  34. import { useEditorContext } from '@/shared/context/editor-context'
  35. export interface GotoOffsetOptions {
  36. gotoOffset: number
  37. }
  38. interface OpenDocOptions
  39. extends Partial<GotoLineOptions>,
  40. Partial<GotoOffsetOptions> {
  41. gotoOffset?: number
  42. forceReopen?: boolean
  43. keepCurrentView?: boolean
  44. }
  45. export type EditorManager = {
  46. getEditorType: () => EditorType | null
  47. showSymbolPalette: boolean
  48. currentDocument: DocumentContainer
  49. currentDocumentId: DocId | null
  50. getCurrentDocValue: () => string | null
  51. getCurrentDocId: () => DocId | null
  52. startIgnoringExternalUpdates: () => void
  53. stopIgnoringExternalUpdates: () => void
  54. openDocId: (docId: string, options?: OpenDocOptions) => void
  55. openDoc: (document: Doc, options?: OpenDocOptions) => void
  56. openDocs: OpenDocuments
  57. openInitialDoc: (docId: string) => void
  58. jumpToLine: (options: GotoLineOptions) => void
  59. wantTrackChanges: boolean
  60. setWantTrackChanges: React.Dispatch<
  61. React.SetStateAction<EditorManager['wantTrackChanges']>
  62. >
  63. debugTimers: React.MutableRefObject<Record<string, number>>
  64. }
  65. function hasGotoLine(options: OpenDocOptions): options is GotoLineOptions {
  66. return typeof options.gotoLine === 'number'
  67. }
  68. function hasGotoOffset(options: OpenDocOptions): options is GotoOffsetOptions {
  69. return typeof options.gotoOffset === 'number'
  70. }
  71. export type EditorScopeValue = {
  72. showSymbolPalette: false
  73. toggleSymbolPalette: () => void
  74. sharejs_doc: DocumentContainer | null
  75. open_doc_id: string | null
  76. open_doc_name: string | null
  77. opening: boolean
  78. trackChanges: boolean
  79. wantTrackChanges: boolean
  80. showVisual: boolean
  81. newSourceEditor: boolean
  82. error_state: boolean
  83. }
  84. export const EditorManagerContext = createContext<EditorManager | undefined>(
  85. undefined
  86. )
  87. export const EditorManagerProvider: FC = ({ children }) => {
  88. const { t } = useTranslation()
  89. const ide = useIdeContext()
  90. const { projectId } = useIdeReactContext()
  91. const { reportError, eventEmitter, eventLog } = useIdeReactContext()
  92. const { setOutOfSync } = useEditorContext()
  93. const { socket, closeConnection, connectionState } = useConnectionContext()
  94. const { view, setView } = useLayoutContext()
  95. const { showGenericMessageModal, genericModalVisible, showOutOfSyncModal } =
  96. useModalsContext()
  97. const [showSymbolPalette, setShowSymbolPalette] = useScopeValue<boolean>(
  98. 'editor.showSymbolPalette'
  99. )
  100. const [showVisual] = useScopeValue<boolean>('editor.showVisual')
  101. const [currentDocument, setCurrentDocument] =
  102. useScopeValue<DocumentContainer>('editor.sharejs_doc')
  103. const [openDocId, setOpenDocId] = useScopeValue<DocId | null>(
  104. 'editor.open_doc_id'
  105. )
  106. const [, setOpenDocName] = useScopeValue<string | null>(
  107. 'editor.open_doc_name'
  108. )
  109. const [, setOpening] = useScopeValue<boolean>('editor.opening')
  110. const [, setIsInErrorState] = useScopeValue<boolean>('editor.error_state')
  111. const [, setTrackChanges] = useScopeValue<boolean>('editor.trackChanges')
  112. const [wantTrackChanges, setWantTrackChanges] = useScopeValue<boolean>(
  113. 'editor.wantTrackChanges'
  114. )
  115. const wantTrackChangesRef = useRef(wantTrackChanges)
  116. useEffect(() => {
  117. wantTrackChangesRef.current = wantTrackChanges
  118. }, [wantTrackChanges])
  119. const goToLineEmitter = useScopeEventEmitter('editor:gotoLine')
  120. const { fileTreeData } = useFileTreeData()
  121. const [ignoringExternalUpdates, setIgnoringExternalUpdates] = useState(false)
  122. const { createDebugDiff, debugTimers } = useDebugDiffTracker(
  123. projectId,
  124. currentDocument
  125. )
  126. const [globalEditorWatchdogManager] = useState(
  127. () =>
  128. new EditorWatchdogManager({
  129. onTimeoutHandler: (meta: Record<string, any>) => {
  130. let diffSize: number | null = null
  131. createDebugDiff()
  132. .then(calculatedDiffSize => {
  133. diffSize = calculatedDiffSize
  134. })
  135. .finally(() => {
  136. sendMB('losing-edits', {
  137. ...meta,
  138. diffSize,
  139. timers: debugTimers.current,
  140. })
  141. reportError('losing-edits', {
  142. ...meta,
  143. diffSize,
  144. timers: debugTimers.current,
  145. })
  146. })
  147. },
  148. })
  149. )
  150. // Store the most recent document error and consume it in an effect, which
  151. // prevents circular dependencies in useCallbacks
  152. const [docError, setDocError] = useState<{
  153. doc: Doc
  154. document: DocumentContainer
  155. error: Error | string
  156. meta?: Record<string, any>
  157. editorContent?: string
  158. } | null>(null)
  159. const [docTooLongErrorShown, setDocTooLongErrorShown] = useState(false)
  160. useEffect(() => {
  161. if (!genericModalVisible) {
  162. setDocTooLongErrorShown(false)
  163. }
  164. }, [genericModalVisible])
  165. const [openDocs] = useState(
  166. () =>
  167. new OpenDocuments(
  168. socket,
  169. globalEditorWatchdogManager,
  170. eventEmitter,
  171. eventLog
  172. )
  173. )
  174. const openDocIdStorageKey = `doc.open_id.${projectId}`
  175. // Persist the open document ID to local storage
  176. useEffect(() => {
  177. if (openDocId) {
  178. customLocalStorage.setItem(openDocIdStorageKey, openDocId)
  179. }
  180. }, [openDocId, openDocIdStorageKey])
  181. const editorOpenDocEpochRef = useRef(0)
  182. // TODO: This looks dodgy because it wraps a state setter and is itself
  183. // stored in React state in the scope store. The problem is that it needs to
  184. // be exposed via the scope store because some components access it that way;
  185. // it would be better to simply access it from a context, but the current
  186. // implementation in EditorManager interacts with Angular scope to update
  187. // the layout. Once Angular is gone, this can become a context method.
  188. useEffect(() => {
  189. ide.scopeStore.set('editor.toggleSymbolPalette', () => {
  190. setShowSymbolPalette(show => {
  191. const newValue = !show
  192. sendMB(newValue ? 'symbol-palette-show' : 'symbol-palette-hide')
  193. return newValue
  194. })
  195. })
  196. }, [ide.scopeStore, setShowSymbolPalette])
  197. const getEditorType = useCallback((): EditorType | null => {
  198. if (!currentDocument) {
  199. return null
  200. }
  201. return showVisual ? 'cm6-rich-text' : 'cm6'
  202. }, [currentDocument, showVisual])
  203. const getCurrentDocValue = useCallback(() => {
  204. return currentDocument?.getSnapshot() ?? null
  205. }, [currentDocument])
  206. const getCurrentDocId = useCallback(() => openDocId, [openDocId])
  207. const startIgnoringExternalUpdates = useCallback(
  208. () => setIgnoringExternalUpdates(true),
  209. []
  210. )
  211. const stopIgnoringExternalUpdates = useCallback(
  212. () => setIgnoringExternalUpdates(false),
  213. []
  214. )
  215. const jumpToLine = useCallback(
  216. (options: GotoLineOptions) => {
  217. goToLineEmitter(options)
  218. },
  219. [goToLineEmitter]
  220. )
  221. const unbindFromDocumentEvents = (document: DocumentContainer) => {
  222. document.off()
  223. }
  224. const attachErrorHandlerToDocument = useCallback(
  225. (doc: Doc, document: DocumentContainer) => {
  226. document.on(
  227. 'error',
  228. (
  229. error: Error | string,
  230. meta?: Record<string, any>,
  231. editorContent?: string
  232. ) => {
  233. setDocError({ doc, document, error, meta, editorContent })
  234. }
  235. )
  236. },
  237. []
  238. )
  239. const bindToDocumentEvents = useCallback(
  240. (doc: Doc, document: DocumentContainer) => {
  241. attachErrorHandlerToDocument(doc, document)
  242. document.on('externalUpdate', (update: Update) => {
  243. if (ignoringExternalUpdates) {
  244. return
  245. }
  246. if (
  247. update.meta.type === 'external' &&
  248. update.meta.source === 'git-bridge'
  249. ) {
  250. return
  251. }
  252. if (
  253. update.meta.origin?.kind === 'file-restore' ||
  254. update.meta.origin?.kind === 'project-restore'
  255. ) {
  256. return
  257. }
  258. showGenericMessageModal(
  259. t('document_updated_externally'),
  260. t('document_updated_externally_detail')
  261. )
  262. })
  263. },
  264. [
  265. attachErrorHandlerToDocument,
  266. ignoringExternalUpdates,
  267. showGenericMessageModal,
  268. t,
  269. ]
  270. )
  271. const syncTimeoutRef = useRef<number | null>(null)
  272. const syncTrackChangesState = useCallback(
  273. (doc: DocumentContainer) => {
  274. if (!doc) {
  275. return
  276. }
  277. if (syncTimeoutRef.current) {
  278. window.clearTimeout(syncTimeoutRef.current)
  279. syncTimeoutRef.current = null
  280. }
  281. const want = wantTrackChangesRef.current
  282. const have = doc.getTrackingChanges()
  283. if (want === have) {
  284. setTrackChanges(want)
  285. return
  286. }
  287. const tryToggle = () => {
  288. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  289. if (saved) {
  290. doc.setTrackingChanges(want)
  291. setTrackChanges(want)
  292. } else {
  293. syncTimeoutRef.current = window.setTimeout(tryToggle, 100)
  294. }
  295. }
  296. tryToggle()
  297. },
  298. [setTrackChanges]
  299. )
  300. const doOpenNewDocument = useCallback(
  301. (doc: Doc) =>
  302. new Promise<DocumentContainer>((resolve, reject) => {
  303. debugConsole.log('[doOpenNewDocument] Opening...')
  304. const newDocument = openDocs.getDocument(doc._id)
  305. if (!newDocument) {
  306. debugConsole.error(`No open document with ID '${doc._id}' found`)
  307. reject(new Error('no open document found'))
  308. return
  309. }
  310. const preJoinEpoch = ++editorOpenDocEpochRef.current
  311. newDocument.join(error => {
  312. if (error) {
  313. debugConsole.log(
  314. `[doOpenNewDocument] error joining doc ${doc._id}`,
  315. error
  316. )
  317. reject(error)
  318. return
  319. }
  320. if (editorOpenDocEpochRef.current !== preJoinEpoch) {
  321. debugConsole.log(
  322. `[doOpenNewDocument] editorOpenDocEpoch mismatch ${editorOpenDocEpochRef.current} vs ${preJoinEpoch}`
  323. )
  324. newDocument.leaveAndCleanUp()
  325. reject(new Error('another document was loaded'))
  326. }
  327. bindToDocumentEvents(doc, newDocument)
  328. resolve(newDocument)
  329. })
  330. }),
  331. [bindToDocumentEvents, openDocs]
  332. )
  333. const openNewDocument = useCallback(
  334. async (doc: Doc): Promise<DocumentContainer> => {
  335. // Leave the current document
  336. // - when we are opening a different new one, to avoid race conditions
  337. // between leaving and joining the same document
  338. // - when the current one has pending ops that need flushing, to avoid
  339. // race conditions from cleanup
  340. const currentDocId = currentDocument?.doc_id
  341. const hasBufferedOps = currentDocument?.hasBufferedOps()
  342. const changingDoc = currentDocument && currentDocId !== doc._id
  343. if (changingDoc || hasBufferedOps) {
  344. debugConsole.log('[openNewDocument] Leaving existing open doc...')
  345. // Do not trigger any UI changes from remote operations
  346. unbindFromDocumentEvents(currentDocument)
  347. // Keep listening for out-of-sync and similar errors.
  348. attachErrorHandlerToDocument(doc, currentDocument)
  349. // Teardown the Document -> ShareJsDoc -> sharejs doc
  350. // By the time this completes, the Document instance is no longer
  351. // registered in OpenDocuments and doOpenNewDocument can start
  352. // from scratch -- read: no corrupted internal state.
  353. const preLeaveEpoch = ++editorOpenDocEpochRef.current
  354. try {
  355. await currentDocument.leaveAndCleanUpPromise()
  356. } catch (error) {
  357. debugConsole.log(
  358. `[openNewDocument] error leaving doc ${currentDocId}`,
  359. error
  360. )
  361. throw error
  362. }
  363. if (editorOpenDocEpochRef.current !== preLeaveEpoch) {
  364. debugConsole.log(
  365. `[openNewDocument] editorOpenDocEpoch mismatch ${editorOpenDocEpochRef.current} vs ${preLeaveEpoch}`
  366. )
  367. throw new Error('another document was loaded')
  368. }
  369. }
  370. return doOpenNewDocument(doc)
  371. },
  372. [attachErrorHandlerToDocument, doOpenNewDocument, currentDocument]
  373. )
  374. const openDocIdRef = useRef(openDocId)
  375. useEffect(() => {
  376. openDocIdRef.current = openDocId
  377. }, [openDocId])
  378. const openDoc = useCallback(
  379. async (doc: Doc, options: OpenDocOptions = {}) => {
  380. debugConsole.log(`[openDoc] Opening ${doc._id}`)
  381. const { promise, resolve, reject } = Promise.withResolvers<Doc>()
  382. if (view === 'editor') {
  383. // store position of previous doc before switching docs
  384. eventEmitter.emit('store-doc-position')
  385. }
  386. if (!options.keepCurrentView) {
  387. setView('editor')
  388. }
  389. const done = (isNewDoc: boolean) => {
  390. window.dispatchEvent(
  391. new CustomEvent('doc:after-opened', {
  392. detail: { isNewDoc, docId: doc._id },
  393. })
  394. )
  395. if (hasGotoLine(options)) {
  396. window.setTimeout(() => jumpToLine(options))
  397. // Jump to the line again after a stored scroll position has been restored
  398. if (isNewDoc) {
  399. window.addEventListener(
  400. 'editor:scroll-position-restored',
  401. () => jumpToLine(options),
  402. { once: true }
  403. )
  404. }
  405. } else if (hasGotoOffset(options)) {
  406. window.setTimeout(() => {
  407. eventEmitter.emit('editor:gotoOffset', options)
  408. })
  409. }
  410. resolve(doc)
  411. }
  412. // If we already have the document open, or are opening the document, we can return at this point.
  413. // Note: only use forceReopen:true to override this when the document is
  414. // out of sync and needs to be reloaded from the server.
  415. if (doc._id === openDocIdRef.current && !options.forceReopen) {
  416. done(false)
  417. return
  418. }
  419. // We're now either opening a new document or reloading a broken one.
  420. openDocIdRef.current = doc._id as DocId
  421. setOpenDocId(doc._id as DocId)
  422. setOpenDocName(doc.name)
  423. setOpening(true)
  424. try {
  425. const document = await openNewDocument(doc)
  426. syncTrackChangesState(document)
  427. setOpening(false)
  428. setCurrentDocument(document)
  429. done(true)
  430. } catch (error: any) {
  431. if (error?.message === 'another document was loaded') {
  432. debugConsole.log(
  433. `[openDoc] another document was loaded while ${doc._id} was loading`
  434. )
  435. return
  436. }
  437. debugConsole.error('Error opening document', error)
  438. showGenericMessageModal(
  439. t('error_opening_document'),
  440. t('error_opening_document_detail')
  441. )
  442. reject(error)
  443. }
  444. return promise
  445. },
  446. [
  447. eventEmitter,
  448. jumpToLine,
  449. openNewDocument,
  450. setCurrentDocument,
  451. setOpenDocId,
  452. setOpenDocName,
  453. setOpening,
  454. setView,
  455. showGenericMessageModal,
  456. syncTrackChangesState,
  457. t,
  458. view,
  459. ]
  460. )
  461. const openDocWithId = useCallback(
  462. (docId: string, options: OpenDocOptions = {}) => {
  463. const doc = findDocEntityById(fileTreeData, docId)
  464. if (!doc) {
  465. return
  466. }
  467. openDoc(doc, options)
  468. },
  469. [fileTreeData, openDoc]
  470. )
  471. const openInitialDoc = useCallback(
  472. (fallbackDocId: string) => {
  473. const docId =
  474. customLocalStorage.getItem(openDocIdStorageKey) || fallbackDocId
  475. if (docId) {
  476. openDocWithId(docId)
  477. }
  478. },
  479. [openDocIdStorageKey, openDocWithId]
  480. )
  481. useEffect(() => {
  482. if (docError) {
  483. const { doc, document, error, meta } = docError
  484. let { editorContent } = docError
  485. const message = typeof error === 'string' ? error : (error?.message ?? '')
  486. // Clear document error so that it's only handled once
  487. setDocError(null)
  488. if (message.includes('maxDocLength')) {
  489. openDoc(doc, { forceReopen: true })
  490. const hasTrackedDeletes =
  491. document.ranges != null &&
  492. document.ranges.changes.some(change => 'd' in change.op)
  493. const explanation = hasTrackedDeletes
  494. ? `${t('document_too_long_detail')} ${t('document_too_long_tracked_deletes')}`
  495. : t('document_too_long_detail')
  496. showGenericMessageModal(t('document_too_long'), explanation)
  497. setDocTooLongErrorShown(true)
  498. } else if (/too many comments or tracked changes/.test(message)) {
  499. showGenericMessageModal(
  500. t('too_many_comments_or_tracked_changes'),
  501. t('too_many_comments_or_tracked_changes_detail')
  502. )
  503. } else if (!docTooLongErrorShown) {
  504. // Do not allow this doc to open another error modal.
  505. document.off('error')
  506. // Preserve the sharejs contents before the teardown.
  507. // eslint-disable-next-line no-unused-vars
  508. editorContent =
  509. typeof editorContent === 'string'
  510. ? editorContent
  511. : document.doc?._doc.snapshot
  512. // Tear down the ShareJsDoc.
  513. if (document.doc) document.doc.clearInflightAndPendingOps()
  514. // Do not re-join after re-connecting.
  515. document.leaveAndCleanUp()
  516. closeConnection('out-of-sync')
  517. reportError(error, meta)
  518. // Tell the user about the error state.
  519. setIsInErrorState(true)
  520. // Ensure that the editor is locked
  521. setOutOfSync(true)
  522. // Display the "out of sync" modal
  523. showOutOfSyncModal(editorContent || '')
  524. // Do not forceReopen the document.
  525. return
  526. }
  527. const handleProjectJoined = () => {
  528. openDoc(doc, { forceReopen: true })
  529. }
  530. eventEmitter.once('project:joined', handleProjectJoined)
  531. return () => {
  532. eventEmitter.off('project:joined', handleProjectJoined)
  533. }
  534. }
  535. }, [
  536. closeConnection,
  537. docError,
  538. docTooLongErrorShown,
  539. eventEmitter,
  540. openDoc,
  541. reportError,
  542. setIsInErrorState,
  543. showGenericMessageModal,
  544. showOutOfSyncModal,
  545. setOutOfSync,
  546. t,
  547. ])
  548. useEventListener(
  549. 'editor:insert-symbol',
  550. useCallback(() => {
  551. sendMB('symbol-palette-insert')
  552. }, [])
  553. )
  554. useEventListener(
  555. 'flush-changes',
  556. useCallback(() => {
  557. openDocs.flushAll()
  558. }, [openDocs])
  559. )
  560. useEventListener(
  561. 'blur',
  562. useCallback(() => {
  563. openDocs.flushAll()
  564. }, [openDocs])
  565. )
  566. // Flush changes before disconnecting
  567. useEffect(() => {
  568. if (connectionState.forceDisconnected) {
  569. openDocs.flushAll()
  570. }
  571. }, [connectionState.forceDisconnected, openDocs])
  572. // Watch for changes in wantTrackChanges
  573. const previousWantTrackChangesRef = useRef(wantTrackChanges)
  574. useEffect(() => {
  575. if (wantTrackChanges !== previousWantTrackChangesRef.current) {
  576. previousWantTrackChangesRef.current = wantTrackChanges
  577. syncTrackChangesState(currentDocument)
  578. }
  579. }, [currentDocument, syncTrackChangesState, wantTrackChanges])
  580. const editorManager = useMemo(
  581. () => ({
  582. getEditorType,
  583. showSymbolPalette,
  584. currentDocument,
  585. currentDocumentId: openDocId,
  586. getCurrentDocValue,
  587. getCurrentDocId,
  588. startIgnoringExternalUpdates,
  589. stopIgnoringExternalUpdates,
  590. openDocId: openDocWithId,
  591. openDoc,
  592. openDocs,
  593. openInitialDoc,
  594. jumpToLine,
  595. wantTrackChanges,
  596. setWantTrackChanges,
  597. debugTimers,
  598. }),
  599. [
  600. getEditorType,
  601. showSymbolPalette,
  602. currentDocument,
  603. openDocId,
  604. getCurrentDocValue,
  605. getCurrentDocId,
  606. startIgnoringExternalUpdates,
  607. stopIgnoringExternalUpdates,
  608. openDocWithId,
  609. openDoc,
  610. openDocs,
  611. openInitialDoc,
  612. jumpToLine,
  613. wantTrackChanges,
  614. setWantTrackChanges,
  615. debugTimers,
  616. ]
  617. )
  618. // Expose editorManager via ide object because some React code relies on it,
  619. // for now
  620. ide.editorManager = editorManager
  621. return (
  622. <EditorManagerContext.Provider value={editorManager}>
  623. {children}
  624. </EditorManagerContext.Provider>
  625. )
  626. }
  627. export function useEditorManagerContext(): EditorManager {
  628. const context = useContext(EditorManagerContext)
  629. if (!context) {
  630. throw new Error(
  631. 'useEditorManagerContext is only available inside EditorManagerProvider'
  632. )
  633. }
  634. return context
  635. }