editor-manager-context.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. export const EditorManagerContext = createContext<EditorManager | undefined>(
  84. undefined
  85. )
  86. export const EditorManagerProvider: FC = ({ children }) => {
  87. const { t } = useTranslation()
  88. const ide = useIdeContext()
  89. const { projectId } = useIdeReactContext()
  90. const { reportError, eventEmitter, eventLog } = useIdeReactContext()
  91. const { setOutOfSync } = useEditorContext()
  92. const { socket, disconnect, connectionState } = useConnectionContext()
  93. const { view, setView } = useLayoutContext()
  94. const { showGenericMessageModal, genericModalVisible, showOutOfSyncModal } =
  95. useModalsContext()
  96. const [showSymbolPalette, setShowSymbolPalette] = useScopeValue<boolean>(
  97. 'editor.showSymbolPalette'
  98. )
  99. const [showVisual] = useScopeValue<boolean>('editor.showVisual')
  100. const [currentDocument, setCurrentDocument] =
  101. useScopeValue<DocumentContainer>('editor.sharejs_doc')
  102. const [openDocId, setOpenDocId] = useScopeValue<DocId | null>(
  103. 'editor.open_doc_id'
  104. )
  105. const [, setOpenDocName] = useScopeValue<string | null>(
  106. 'editor.open_doc_name'
  107. )
  108. const [, setOpening] = useScopeValue<boolean>('editor.opening')
  109. const [, setIsInErrorState] = useScopeValue<boolean>('editor.error_state')
  110. const [, setTrackChanges] = useScopeValue<boolean>('editor.trackChanges')
  111. const [wantTrackChanges, setWantTrackChanges] = useScopeValue<boolean>(
  112. 'editor.wantTrackChanges'
  113. )
  114. const wantTrackChangesRef = useRef(wantTrackChanges)
  115. useEffect(() => {
  116. wantTrackChangesRef.current = wantTrackChanges
  117. }, [wantTrackChanges])
  118. const goToLineEmitter = useScopeEventEmitter('editor:gotoLine')
  119. const { fileTreeData } = useFileTreeData()
  120. const [ignoringExternalUpdates, setIgnoringExternalUpdates] = useState(false)
  121. const { createDebugDiff, debugTimers } = useDebugDiffTracker(
  122. projectId,
  123. currentDocument
  124. )
  125. const [globalEditorWatchdogManager] = useState(
  126. () =>
  127. new EditorWatchdogManager({
  128. onTimeoutHandler: (meta: Record<string, any>) => {
  129. let diffSize: number | null = null
  130. createDebugDiff()
  131. .then(calculatedDiffSize => {
  132. diffSize = calculatedDiffSize
  133. })
  134. .finally(() => {
  135. sendMB('losing-edits', {
  136. ...meta,
  137. diffSize,
  138. timers: debugTimers.current,
  139. })
  140. reportError('losing-edits', {
  141. ...meta,
  142. diffSize,
  143. timers: debugTimers.current,
  144. })
  145. })
  146. },
  147. })
  148. )
  149. // Store the most recent document error and consume it in an effect, which
  150. // prevents circular dependencies in useCallbacks
  151. const [docError, setDocError] = useState<{
  152. doc: Doc
  153. document: DocumentContainer
  154. error: Error | string
  155. meta?: Record<string, any>
  156. editorContent?: string
  157. } | null>(null)
  158. const [docTooLongErrorShown, setDocTooLongErrorShown] = useState(false)
  159. useEffect(() => {
  160. if (!genericModalVisible) {
  161. setDocTooLongErrorShown(false)
  162. }
  163. }, [genericModalVisible])
  164. const [openDocs] = useState(
  165. () =>
  166. new OpenDocuments(
  167. socket,
  168. globalEditorWatchdogManager,
  169. eventEmitter,
  170. eventLog
  171. )
  172. )
  173. const openDocIdStorageKey = `doc.open_id.${projectId}`
  174. // Persist the open document ID to local storage
  175. useEffect(() => {
  176. if (openDocId) {
  177. customLocalStorage.setItem(openDocIdStorageKey, openDocId)
  178. }
  179. }, [openDocId, openDocIdStorageKey])
  180. const editorOpenDocEpochRef = useRef(0)
  181. // TODO: This looks dodgy because it wraps a state setter and is itself
  182. // stored in React state in the scope store. The problem is that it needs to
  183. // be exposed via the scope store because some components access it that way;
  184. // it would be better to simply access it from a context, but the current
  185. // implementation in EditorManager interacts with Angular scope to update
  186. // the layout. Once Angular is gone, this can become a context method.
  187. useEffect(() => {
  188. ide.scopeStore.set('editor.toggleSymbolPalette', () => {
  189. setShowSymbolPalette(show => {
  190. const newValue = !show
  191. sendMB(newValue ? 'symbol-palette-show' : 'symbol-palette-hide')
  192. return newValue
  193. })
  194. })
  195. }, [ide.scopeStore, setShowSymbolPalette])
  196. const getEditorType = useCallback((): EditorType | null => {
  197. if (!currentDocument) {
  198. return null
  199. }
  200. return showVisual ? 'cm6-rich-text' : 'cm6'
  201. }, [currentDocument, showVisual])
  202. const getCurrentDocValue = useCallback(() => {
  203. return currentDocument?.getSnapshot() ?? null
  204. }, [currentDocument])
  205. const getCurrentDocId = useCallback(() => openDocId, [openDocId])
  206. const startIgnoringExternalUpdates = useCallback(
  207. () => setIgnoringExternalUpdates(true),
  208. []
  209. )
  210. const stopIgnoringExternalUpdates = useCallback(
  211. () => setIgnoringExternalUpdates(false),
  212. []
  213. )
  214. const jumpToLine = useCallback(
  215. (options: GotoLineOptions) => {
  216. goToLineEmitter(
  217. options.gotoLine,
  218. options.gotoColumn ?? 0,
  219. options.syncToPdf ?? false
  220. )
  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 (update.meta.source === 'file-revert') {
  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. if (view === 'editor') {
  382. // store position of previous doc before switching docs
  383. eventEmitter.emit('store-doc-position')
  384. }
  385. setView('editor')
  386. const done = (isNewDoc: boolean) => {
  387. window.dispatchEvent(
  388. new CustomEvent('doc:after-opened', {
  389. detail: { isNewDoc, docId: doc._id },
  390. })
  391. )
  392. if (hasGotoLine(options)) {
  393. window.setTimeout(() => jumpToLine(options))
  394. // Jump to the line again after a stored scroll position has been restored
  395. if (isNewDoc) {
  396. window.addEventListener(
  397. 'editor:scroll-position-restored',
  398. () => jumpToLine(options),
  399. { once: true }
  400. )
  401. }
  402. } else if (hasGotoOffset(options)) {
  403. window.setTimeout(() => {
  404. eventEmitter.emit('editor:gotoOffset', options.gotoOffset)
  405. })
  406. }
  407. }
  408. // If we already have the document open, or are opening the document, we can return at this point.
  409. // Note: only use forceReopen:true to override this when the document is
  410. // out of sync and needs to be reloaded from the server.
  411. if (doc._id === openDocIdRef.current && !options.forceReopen) {
  412. done(false)
  413. return
  414. }
  415. // We're now either opening a new document or reloading a broken one.
  416. openDocIdRef.current = doc._id as DocId
  417. setOpenDocId(doc._id as DocId)
  418. setOpenDocName(doc.name)
  419. setOpening(true)
  420. try {
  421. const document = await openNewDocument(doc)
  422. syncTrackChangesState(document)
  423. eventEmitter.emit('doc:opened')
  424. setOpening(false)
  425. setCurrentDocument(document)
  426. done(true)
  427. } catch (error: any) {
  428. if (error?.message === 'another document was loaded') {
  429. debugConsole.log(
  430. `[openDoc] another document was loaded while ${doc._id} was loading`
  431. )
  432. return
  433. }
  434. debugConsole.error('Error opening document', error)
  435. showGenericMessageModal(
  436. t('error_opening_document'),
  437. t('error_opening_document_detail')
  438. )
  439. }
  440. },
  441. [
  442. eventEmitter,
  443. jumpToLine,
  444. openNewDocument,
  445. setCurrentDocument,
  446. setOpenDocId,
  447. setOpenDocName,
  448. setOpening,
  449. setView,
  450. showGenericMessageModal,
  451. syncTrackChangesState,
  452. t,
  453. view,
  454. ]
  455. )
  456. const openDocWithId = useCallback(
  457. (docId: string, options: OpenDocOptions = {}) => {
  458. const doc = findDocEntityById(fileTreeData, docId)
  459. if (!doc) {
  460. return
  461. }
  462. openDoc(doc, options)
  463. },
  464. [fileTreeData, openDoc]
  465. )
  466. const openInitialDoc = useCallback(
  467. (fallbackDocId: string) => {
  468. const docId =
  469. customLocalStorage.getItem(openDocIdStorageKey) || fallbackDocId
  470. if (docId) {
  471. openDocWithId(docId)
  472. }
  473. },
  474. [openDocIdStorageKey, openDocWithId]
  475. )
  476. useEffect(() => {
  477. if (docError) {
  478. const { doc, document, error, meta } = docError
  479. let { editorContent } = docError
  480. const message = typeof error === 'string' ? error : error?.message ?? ''
  481. // Clear document error so that it's only handled once
  482. setDocError(null)
  483. if (message.includes('maxDocLength')) {
  484. openDoc(doc, { forceReopen: true })
  485. showGenericMessageModal(
  486. t('document_too_long'),
  487. t('document_too_long_detail')
  488. )
  489. setDocTooLongErrorShown(true)
  490. } else if (/too many comments or tracked changes/.test(message)) {
  491. showGenericMessageModal(
  492. t('too_many_comments_or_tracked_changes'),
  493. t('too_many_comments_or_tracked_changes_detail')
  494. )
  495. } else if (!docTooLongErrorShown) {
  496. // Do not allow this doc to open another error modal.
  497. document.off('error')
  498. // Preserve the sharejs contents before the teardown.
  499. // eslint-disable-next-line no-unused-vars
  500. editorContent =
  501. typeof editorContent === 'string'
  502. ? editorContent
  503. : document.doc?._doc.snapshot
  504. // Tear down the ShareJsDoc.
  505. if (document.doc) document.doc.clearInflightAndPendingOps()
  506. // Do not re-join after re-connecting.
  507. document.leaveAndCleanUp()
  508. disconnect()
  509. reportError(error, meta)
  510. // Tell the user about the error state.
  511. setIsInErrorState(true)
  512. // Ensure that the editor is locked
  513. setOutOfSync(true)
  514. // Display the "out of sync" modal
  515. showOutOfSyncModal(editorContent || '')
  516. // Do not forceReopen the document.
  517. return
  518. }
  519. const handleProjectJoined = () => {
  520. openDoc(doc, { forceReopen: true })
  521. }
  522. eventEmitter.once('project:joined', handleProjectJoined)
  523. return () => {
  524. eventEmitter.off('project:joined', handleProjectJoined)
  525. }
  526. }
  527. }, [
  528. disconnect,
  529. docError,
  530. docTooLongErrorShown,
  531. eventEmitter,
  532. openDoc,
  533. reportError,
  534. setIsInErrorState,
  535. showGenericMessageModal,
  536. showOutOfSyncModal,
  537. setOutOfSync,
  538. t,
  539. ])
  540. useEventListener('editor:insert-symbol', () => {
  541. sendMB('symbol-palette-insert')
  542. })
  543. useEventListener('flush-changes', () => {
  544. openDocs.flushAll()
  545. })
  546. useEventListener('blur', () => {
  547. openDocs.flushAll()
  548. })
  549. // Flush changes before disconnecting
  550. useEffect(() => {
  551. if (connectionState.forceDisconnected) {
  552. openDocs.flushAll()
  553. }
  554. }, [connectionState.forceDisconnected, openDocs])
  555. // Watch for changes in wantTrackChanges
  556. const previousWantTrackChangesRef = useRef(wantTrackChanges)
  557. useEffect(() => {
  558. if (wantTrackChanges !== previousWantTrackChangesRef.current) {
  559. previousWantTrackChangesRef.current = wantTrackChanges
  560. syncTrackChangesState(currentDocument)
  561. }
  562. }, [currentDocument, syncTrackChangesState, wantTrackChanges])
  563. const editorManager = useMemo(
  564. () => ({
  565. getEditorType,
  566. showSymbolPalette,
  567. currentDocument,
  568. currentDocumentId: openDocId,
  569. getCurrentDocValue,
  570. getCurrentDocId,
  571. startIgnoringExternalUpdates,
  572. stopIgnoringExternalUpdates,
  573. openDocId: openDocWithId,
  574. openDoc,
  575. openDocs,
  576. openInitialDoc,
  577. jumpToLine,
  578. wantTrackChanges,
  579. setWantTrackChanges,
  580. debugTimers,
  581. }),
  582. [
  583. getEditorType,
  584. showSymbolPalette,
  585. currentDocument,
  586. openDocId,
  587. getCurrentDocValue,
  588. getCurrentDocId,
  589. startIgnoringExternalUpdates,
  590. stopIgnoringExternalUpdates,
  591. openDocWithId,
  592. openDoc,
  593. openDocs,
  594. openInitialDoc,
  595. jumpToLine,
  596. wantTrackChanges,
  597. setWantTrackChanges,
  598. debugTimers,
  599. ]
  600. )
  601. // Expose editorManager via ide object because some React code relies on it,
  602. // for now
  603. ide.editorManager = editorManager
  604. return (
  605. <EditorManagerContext.Provider value={editorManager}>
  606. {children}
  607. </EditorManagerContext.Provider>
  608. )
  609. }
  610. export function useEditorManagerContext(): EditorManager {
  611. const context = useContext(EditorManagerContext)
  612. if (!context) {
  613. throw new Error(
  614. 'useEditorManagerContext is only available inside EditorManagerProvider'
  615. )
  616. }
  617. return context
  618. }