open-documents.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Migrated from static methods of Document in Document.js
  2. import { Document } from '@/features/ide-react/editor/document'
  3. import { debugConsole } from '@/utils/debugging'
  4. import { Socket } from '@/features/ide-react/connection/types/socket'
  5. import { IdeEventEmitter } from '@/features/ide-react/create-ide-event-emitter'
  6. import { EventLog } from '@/features/ide-react/editor/event-log'
  7. import EditorWatchdogManager from '@/features/ide-react/connection/editor-watchdog-manager'
  8. export class OpenDocuments {
  9. private openDocs = new Map<string, Document>()
  10. // eslint-disable-next-line no-useless-constructor
  11. constructor(
  12. private readonly socket: Socket,
  13. private readonly globalEditorWatchdogManager: EditorWatchdogManager,
  14. private readonly events: IdeEventEmitter,
  15. private readonly eventLog: EventLog
  16. ) {}
  17. getDocument(docId: string) {
  18. // Try to clean up existing docs before reopening them. If the doc has no
  19. // buffered ops then it will be deleted by _cleanup() and a new instance
  20. // of the document created below. This prevents us trying to follow the
  21. // joinDoc:existing code path on an existing doc that doesn't have any
  22. // local changes and getting an error if its version is too old.
  23. if (this.openDocs.has(docId)) {
  24. debugConsole.log(
  25. `[getDocument] Cleaning up existing document instance for ${docId}`
  26. )
  27. this.openDocs.get(docId)?.cleanUp()
  28. }
  29. if (!this.openDocs.has(docId)) {
  30. debugConsole.log(
  31. `[getDocument] Creating new document instance for ${docId}`
  32. )
  33. this.createDoc(docId)
  34. } else {
  35. debugConsole.log(
  36. `[getDocument] Returning existing document instance for ${docId}`
  37. )
  38. }
  39. return this.openDocs.get(docId)
  40. }
  41. private createDoc(docId: string) {
  42. const doc = new Document(
  43. docId,
  44. this.socket,
  45. this.globalEditorWatchdogManager,
  46. this.events,
  47. this.eventLog
  48. )
  49. this.openDocs.set(docId, doc)
  50. doc.on('detach', () => {
  51. debugConsole.log(
  52. `[detach] Removing document with ID (${docId}) from openDocs`
  53. )
  54. doc.off('detach')
  55. this.openDocs.delete(docId)
  56. })
  57. }
  58. hasUnsavedChanges() {
  59. for (const doc of this.openDocs.values()) {
  60. if (doc.hasBufferedOps()) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. flushAll() {
  67. for (const doc of this.openDocs.values()) {
  68. doc.flush()
  69. }
  70. }
  71. unsavedDocIds() {
  72. const ids = []
  73. for (const [docId, doc] of this.openDocs) {
  74. if (!doc.pollSavedStatus()) {
  75. ids.push(docId)
  76. }
  77. }
  78. return ids
  79. }
  80. }