editor-manager-context.tsx 21 KB

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