editor-manager-context.tsx 20 KB

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