editor-manager-context.tsx 19 KB

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