editor-manager-context.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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. getCurrentDocumentId: () => DocId | null
  52. startIgnoringExternalUpdates: () => void
  53. stopIgnoringExternalUpdates: () => void
  54. openDocWithId: (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 [currentDocumentId, setCurrentDocumentId] = 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 currentDocumentIdStorageKey = `doc.open_id.${projectId}`
  175. // Persist the open document ID to local storage
  176. useEffect(() => {
  177. if (currentDocumentId) {
  178. customLocalStorage.setItem(currentDocumentIdStorageKey, currentDocumentId)
  179. }
  180. }, [currentDocumentId, currentDocumentIdStorageKey])
  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 getCurrentDocumentId = useCallback(
  207. () => currentDocumentId,
  208. [currentDocumentId]
  209. )
  210. const startIgnoringExternalUpdates = useCallback(
  211. () => setIgnoringExternalUpdates(true),
  212. []
  213. )
  214. const stopIgnoringExternalUpdates = useCallback(
  215. () => setIgnoringExternalUpdates(false),
  216. []
  217. )
  218. const jumpToLine = useCallback(
  219. (options: GotoLineOptions) => {
  220. goToLineEmitter(options)
  221. },
  222. [goToLineEmitter]
  223. )
  224. const unbindFromDocumentEvents = (document: DocumentContainer) => {
  225. document.off()
  226. }
  227. const attachErrorHandlerToDocument = useCallback(
  228. (doc: Doc, document: DocumentContainer) => {
  229. document.on(
  230. 'error',
  231. (
  232. error: Error | string,
  233. meta?: Record<string, any>,
  234. editorContent?: string
  235. ) => {
  236. setDocError({ doc, document, error, meta, editorContent })
  237. }
  238. )
  239. },
  240. []
  241. )
  242. const bindToDocumentEvents = useCallback(
  243. (doc: Doc, document: DocumentContainer) => {
  244. attachErrorHandlerToDocument(doc, document)
  245. document.on('externalUpdate', (update: Update) => {
  246. if (ignoringExternalUpdates) {
  247. return
  248. }
  249. if (
  250. update.meta.type === 'external' &&
  251. update.meta.source === 'git-bridge'
  252. ) {
  253. return
  254. }
  255. if (
  256. update.meta.origin?.kind === 'file-restore' ||
  257. update.meta.origin?.kind === 'project-restore'
  258. ) {
  259. return
  260. }
  261. showGenericMessageModal(
  262. t('document_updated_externally'),
  263. t('document_updated_externally_detail')
  264. )
  265. })
  266. },
  267. [
  268. attachErrorHandlerToDocument,
  269. ignoringExternalUpdates,
  270. showGenericMessageModal,
  271. t,
  272. ]
  273. )
  274. const syncTimeoutRef = useRef<number | null>(null)
  275. const syncTrackChangesState = useCallback(
  276. (doc: DocumentContainer) => {
  277. if (!doc) {
  278. return
  279. }
  280. if (syncTimeoutRef.current) {
  281. window.clearTimeout(syncTimeoutRef.current)
  282. syncTimeoutRef.current = null
  283. }
  284. const want = wantTrackChangesRef.current
  285. const have = doc.getTrackingChanges()
  286. if (want === have) {
  287. setTrackChanges(want)
  288. return
  289. }
  290. const tryToggle = () => {
  291. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  292. if (saved) {
  293. doc.setTrackingChanges(want)
  294. setTrackChanges(want)
  295. } else {
  296. syncTimeoutRef.current = window.setTimeout(tryToggle, 100)
  297. }
  298. }
  299. tryToggle()
  300. },
  301. [setTrackChanges]
  302. )
  303. const doOpenNewDocument = useCallback(
  304. (doc: Doc) =>
  305. new Promise<DocumentContainer>((resolve, reject) => {
  306. debugConsole.log('[doOpenNewDocument] Opening...')
  307. const newDocument = openDocs.getDocument(doc._id)
  308. if (!newDocument) {
  309. debugConsole.error(`No open document with ID '${doc._id}' found`)
  310. reject(new Error('no open document found'))
  311. return
  312. }
  313. const preJoinEpoch = ++editorOpenDocEpochRef.current
  314. newDocument.join(error => {
  315. if (error) {
  316. debugConsole.log(
  317. `[doOpenNewDocument] error joining doc ${doc._id}`,
  318. error
  319. )
  320. reject(error)
  321. return
  322. }
  323. if (editorOpenDocEpochRef.current !== preJoinEpoch) {
  324. debugConsole.log(
  325. `[doOpenNewDocument] editorOpenDocEpoch mismatch ${editorOpenDocEpochRef.current} vs ${preJoinEpoch}`
  326. )
  327. newDocument.leaveAndCleanUp()
  328. reject(new Error('another document was loaded'))
  329. }
  330. bindToDocumentEvents(doc, newDocument)
  331. resolve(newDocument)
  332. })
  333. }),
  334. [bindToDocumentEvents, openDocs]
  335. )
  336. const openNewDocument = useCallback(
  337. async (doc: Doc): Promise<DocumentContainer> => {
  338. // Leave the current document
  339. // - when we are opening a different new one, to avoid race conditions
  340. // between leaving and joining the same document
  341. // - when the current one has pending ops that need flushing, to avoid
  342. // race conditions from cleanup
  343. const currentDocumentId = currentDocument?.doc_id
  344. const hasBufferedOps = currentDocument?.hasBufferedOps()
  345. const changingDoc = currentDocument && currentDocumentId !== doc._id
  346. if (changingDoc || hasBufferedOps) {
  347. debugConsole.log('[openNewDocument] Leaving existing open doc...')
  348. // Do not trigger any UI changes from remote operations
  349. unbindFromDocumentEvents(currentDocument)
  350. // Keep listening for out-of-sync and similar errors.
  351. attachErrorHandlerToDocument(doc, currentDocument)
  352. // Teardown the Document -> ShareJsDoc -> sharejs doc
  353. // By the time this completes, the Document instance is no longer
  354. // registered in OpenDocuments and doOpenNewDocument can start
  355. // from scratch -- read: no corrupted internal state.
  356. const preLeaveEpoch = ++editorOpenDocEpochRef.current
  357. try {
  358. await currentDocument.leaveAndCleanUpPromise()
  359. } catch (error) {
  360. debugConsole.log(
  361. `[openNewDocument] error leaving doc ${currentDocumentId}`,
  362. error
  363. )
  364. throw error
  365. }
  366. if (editorOpenDocEpochRef.current !== preLeaveEpoch) {
  367. debugConsole.log(
  368. `[openNewDocument] editorOpenDocEpoch mismatch ${editorOpenDocEpochRef.current} vs ${preLeaveEpoch}`
  369. )
  370. throw new Error('another document was loaded')
  371. }
  372. }
  373. return doOpenNewDocument(doc)
  374. },
  375. [attachErrorHandlerToDocument, doOpenNewDocument, currentDocument]
  376. )
  377. const currentDocumentIdRef = useRef(currentDocumentId)
  378. useEffect(() => {
  379. currentDocumentIdRef.current = currentDocumentId
  380. }, [currentDocumentId])
  381. const openDoc = useCallback(
  382. async (doc: Doc, options: OpenDocOptions = {}) => {
  383. debugConsole.log(`[openDoc] Opening ${doc._id}`)
  384. const { promise, resolve, reject } = Promise.withResolvers<Doc>()
  385. if (view === 'editor') {
  386. // store position of previous doc before switching docs
  387. eventEmitter.emit('store-doc-position')
  388. }
  389. if (!options.keepCurrentView) {
  390. setView('editor')
  391. }
  392. const done = (isNewDoc: boolean) => {
  393. window.dispatchEvent(
  394. new CustomEvent('doc:after-opened', {
  395. detail: { isNewDoc, docId: doc._id },
  396. })
  397. )
  398. if (hasGotoLine(options)) {
  399. window.setTimeout(() => jumpToLine(options))
  400. // Jump to the line again after a stored scroll position has been restored
  401. if (isNewDoc) {
  402. window.addEventListener(
  403. 'editor:scroll-position-restored',
  404. () => jumpToLine(options),
  405. { once: true }
  406. )
  407. }
  408. } else if (hasGotoOffset(options)) {
  409. window.setTimeout(() => {
  410. eventEmitter.emit('editor:gotoOffset', options)
  411. })
  412. }
  413. resolve(doc)
  414. }
  415. // If we already have the document open, or are opening the document, we can return at this point.
  416. // Note: only use forceReopen:true to override this when the document is
  417. // out of sync and needs to be reloaded from the server.
  418. if (doc._id === currentDocumentIdRef.current && !options.forceReopen) {
  419. done(false)
  420. return
  421. }
  422. // We're now either opening a new document or reloading a broken one.
  423. currentDocumentIdRef.current = doc._id as DocId
  424. setCurrentDocumentId(doc._id as DocId)
  425. setOpenDocName(doc.name)
  426. setOpening(true)
  427. try {
  428. const document = await openNewDocument(doc)
  429. syncTrackChangesState(document)
  430. setOpening(false)
  431. setCurrentDocument(document)
  432. done(true)
  433. } catch (error: any) {
  434. if (error?.message === 'another document was loaded') {
  435. debugConsole.log(
  436. `[openDoc] another document was loaded while ${doc._id} was loading`
  437. )
  438. return
  439. }
  440. debugConsole.error('Error opening document', error)
  441. showGenericMessageModal(
  442. t('error_opening_document'),
  443. t('error_opening_document_detail')
  444. )
  445. reject(error)
  446. }
  447. return promise
  448. },
  449. [
  450. eventEmitter,
  451. jumpToLine,
  452. openNewDocument,
  453. setCurrentDocument,
  454. setCurrentDocumentId,
  455. setOpenDocName,
  456. setOpening,
  457. setView,
  458. showGenericMessageModal,
  459. syncTrackChangesState,
  460. t,
  461. view,
  462. ]
  463. )
  464. const openDocWithId = useCallback(
  465. (docId: string, options: OpenDocOptions = {}) => {
  466. const doc = findDocEntityById(fileTreeData, docId)
  467. if (!doc) {
  468. return
  469. }
  470. openDoc(doc, options)
  471. },
  472. [fileTreeData, openDoc]
  473. )
  474. const openInitialDoc = useCallback(
  475. (fallbackDocId: string) => {
  476. const docId =
  477. customLocalStorage.getItem(currentDocumentIdStorageKey) || fallbackDocId
  478. if (docId) {
  479. openDocWithId(docId)
  480. }
  481. },
  482. [currentDocumentIdStorageKey, openDocWithId]
  483. )
  484. useEffect(() => {
  485. if (docError) {
  486. const { doc, document, error, meta } = docError
  487. let { editorContent } = docError
  488. const message = typeof error === 'string' ? error : (error?.message ?? '')
  489. // Clear document error so that it's only handled once
  490. setDocError(null)
  491. if (message.includes('maxDocLength')) {
  492. openDoc(doc, { forceReopen: true })
  493. const hasTrackedDeletes =
  494. document.ranges != null &&
  495. document.ranges.changes.some(change => 'd' in change.op)
  496. const explanation = hasTrackedDeletes
  497. ? `${t('document_too_long_detail')} ${t('document_too_long_tracked_deletes')}`
  498. : t('document_too_long_detail')
  499. showGenericMessageModal(t('document_too_long'), explanation)
  500. setDocTooLongErrorShown(true)
  501. } else if (/too many comments or tracked changes/.test(message)) {
  502. showGenericMessageModal(
  503. t('too_many_comments_or_tracked_changes'),
  504. t('too_many_comments_or_tracked_changes_detail')
  505. )
  506. } else if (!docTooLongErrorShown) {
  507. // Do not allow this doc to open another error modal.
  508. document.off('error')
  509. // Preserve the sharejs contents before the teardown.
  510. // eslint-disable-next-line no-unused-vars
  511. editorContent =
  512. typeof editorContent === 'string'
  513. ? editorContent
  514. : document.doc?._doc.snapshot
  515. // Tear down the ShareJsDoc.
  516. if (document.doc) document.doc.clearInflightAndPendingOps()
  517. // Do not re-join after re-connecting.
  518. document.leaveAndCleanUp()
  519. closeConnection('out-of-sync')
  520. reportError(error, meta)
  521. // Tell the user about the error state.
  522. setIsInErrorState(true)
  523. // Ensure that the editor is locked
  524. setOutOfSync(true)
  525. // Display the "out of sync" modal
  526. showOutOfSyncModal(editorContent || '')
  527. // Do not forceReopen the document.
  528. return
  529. }
  530. const handleProjectJoined = () => {
  531. openDoc(doc, { forceReopen: true })
  532. }
  533. eventEmitter.once('project:joined', handleProjectJoined)
  534. return () => {
  535. eventEmitter.off('project:joined', handleProjectJoined)
  536. }
  537. }
  538. }, [
  539. closeConnection,
  540. docError,
  541. docTooLongErrorShown,
  542. eventEmitter,
  543. openDoc,
  544. reportError,
  545. setIsInErrorState,
  546. showGenericMessageModal,
  547. showOutOfSyncModal,
  548. setOutOfSync,
  549. t,
  550. ])
  551. useEventListener(
  552. 'editor:insert-symbol',
  553. useCallback(() => {
  554. sendMB('symbol-palette-insert')
  555. }, [])
  556. )
  557. useEventListener(
  558. 'flush-changes',
  559. useCallback(() => {
  560. openDocs.flushAll()
  561. }, [openDocs])
  562. )
  563. useEventListener(
  564. 'blur',
  565. useCallback(() => {
  566. openDocs.flushAll()
  567. }, [openDocs])
  568. )
  569. // Flush changes before disconnecting
  570. useEffect(() => {
  571. if (connectionState.forceDisconnected) {
  572. openDocs.flushAll()
  573. }
  574. }, [connectionState.forceDisconnected, openDocs])
  575. // Watch for changes in wantTrackChanges
  576. const previousWantTrackChangesRef = useRef(wantTrackChanges)
  577. useEffect(() => {
  578. if (wantTrackChanges !== previousWantTrackChangesRef.current) {
  579. previousWantTrackChangesRef.current = wantTrackChanges
  580. syncTrackChangesState(currentDocument)
  581. }
  582. }, [currentDocument, syncTrackChangesState, wantTrackChanges])
  583. const editorManager = useMemo(
  584. () => ({
  585. getEditorType,
  586. showSymbolPalette,
  587. currentDocument,
  588. currentDocumentId,
  589. getCurrentDocValue,
  590. getCurrentDocumentId,
  591. startIgnoringExternalUpdates,
  592. stopIgnoringExternalUpdates,
  593. openDocWithId,
  594. openDoc,
  595. openDocs,
  596. openInitialDoc,
  597. jumpToLine,
  598. wantTrackChanges,
  599. setWantTrackChanges,
  600. debugTimers,
  601. }),
  602. [
  603. getEditorType,
  604. showSymbolPalette,
  605. currentDocument,
  606. currentDocumentId,
  607. getCurrentDocValue,
  608. getCurrentDocumentId,
  609. startIgnoringExternalUpdates,
  610. stopIgnoringExternalUpdates,
  611. openDocWithId,
  612. openDoc,
  613. openDocs,
  614. openInitialDoc,
  615. jumpToLine,
  616. wantTrackChanges,
  617. setWantTrackChanges,
  618. debugTimers,
  619. ]
  620. )
  621. // Expose editorManager via ide object because some React code relies on it,
  622. // for now
  623. ide.editorManager = editorManager
  624. return (
  625. <EditorManagerContext.Provider value={editorManager}>
  626. {children}
  627. </EditorManagerContext.Provider>
  628. )
  629. }
  630. export function useEditorManagerContext(): EditorManager {
  631. const context = useContext(EditorManagerContext)
  632. if (!context) {
  633. throw new Error(
  634. 'useEditorManagerContext is only available inside EditorManagerProvider'
  635. )
  636. }
  637. return context
  638. }