realtime.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import { Prec, Transaction, Annotation } from '@codemirror/state'
  2. import { EditorView, ViewPlugin } from '@codemirror/view'
  3. import { EventEmitter } from 'events'
  4. import { CurrentDoc } from '../../../../../types/current-doc'
  5. import { ShareDoc } from '../../../../../types/share-doc'
  6. import { debugConsole } from '@/utils/debugging'
  7. /*
  8. * Integrate CodeMirror 6 with the real-time system, via ShareJS.
  9. *
  10. * Changes from CodeMirror are passed to the shareDoc
  11. * via `handleTransaction`, while changes arriving from
  12. * real-time are passed to CodeMirror via the EditorFacade.
  13. *
  14. * We use an `EditorFacade` to integrate with the rest of
  15. * the IDE, providing an interface the other systems can work with.
  16. *
  17. * Related files:
  18. * - frontend/js/ide/editor/Document.js
  19. * - frontend/js/ide/editor/ShareJsDoc.js
  20. * - frontend/js/ide/connection/EditorWatchdogManager.js
  21. */
  22. /**
  23. * A custom extension that connects the CodeMirror 6 editor to the currently open ShareJS document.
  24. */
  25. export const realtime = (
  26. { currentDoc }: { currentDoc: CurrentDoc },
  27. handleError: (error: Error) => void
  28. ) => {
  29. const realtimePlugin = ViewPlugin.define(view => {
  30. const editor = new EditorFacade(view)
  31. currentDoc.attachToCM6(editor)
  32. return {
  33. update(update) {
  34. if (update.docChanged) {
  35. editor.handleUpdateFromCM(update.transactions)
  36. }
  37. },
  38. destroy() {
  39. // TODO: wrap in a timeout so processing can finish?
  40. // window.setTimeout(() => {
  41. currentDoc.detachFromCM6()
  42. // }, 0)
  43. },
  44. }
  45. })
  46. // NOTE: not a view plugin, so shouldn't get removed
  47. const ensureRealtimePlugin = EditorView.updateListener.of(update => {
  48. if (!update.view.plugin(realtimePlugin)) {
  49. const message = 'The realtime extension has been destroyed!!'
  50. debugConsole.warn(message)
  51. if (currentDoc.doc) {
  52. // display the "out of sync" modal
  53. currentDoc.doc.emit('error', message)
  54. } else {
  55. // display the error boundary
  56. handleError(new Error(message))
  57. }
  58. }
  59. })
  60. return Prec.highest([realtimePlugin, ensureRealtimePlugin])
  61. }
  62. export class EditorFacade extends EventEmitter {
  63. public shareDoc: ShareDoc | null
  64. public events: EventEmitter
  65. private maxDocLength?: number
  66. constructor(public view: EditorView) {
  67. super()
  68. this.view = view
  69. this.shareDoc = null
  70. this.events = new EventEmitter()
  71. }
  72. getValue() {
  73. return this.view.state.doc.toString()
  74. }
  75. // Dispatch changes to CodeMirror view
  76. cmInsert(position: number, text: string, origin?: string) {
  77. this.view.dispatch({
  78. changes: { from: position, insert: text },
  79. annotations: [
  80. Transaction.remote.of(origin === 'remote'),
  81. Transaction.addToHistory.of(origin !== 'remote'),
  82. ],
  83. })
  84. }
  85. cmDelete(position: number, text: string, origin?: string) {
  86. this.view.dispatch({
  87. changes: { from: position, to: position + text.length },
  88. annotations: [
  89. Transaction.remote.of(origin === 'remote'),
  90. Transaction.addToHistory.of(origin !== 'remote'),
  91. ],
  92. })
  93. }
  94. // Connect to ShareJS, passing changes to the CodeMirror view
  95. // as new transactions.
  96. // This is a broad immitation of helper functions supplied in
  97. // the sharejs library. (See vendor/libs/sharejs, in particular
  98. // the 'attach_ace' helper)
  99. attachShareJs(shareDoc: ShareDoc, maxDocLength?: number) {
  100. this.shareDoc = shareDoc
  101. this.maxDocLength = maxDocLength
  102. const check = () => {
  103. // run in a timeout so it checks the editor content once this update has been applied
  104. window.setTimeout(() => {
  105. const editorText = this.getValue()
  106. const otText = shareDoc.getText()
  107. if (editorText !== otText) {
  108. shareDoc.emit('error', 'Text does not match in CodeMirror 6')
  109. debugConsole.error('Text does not match!')
  110. debugConsole.error('editor: ' + editorText)
  111. debugConsole.error('ot: ' + otText)
  112. }
  113. }, 0)
  114. }
  115. const onInsert = (pos: number, text: string) => {
  116. this.cmInsert(pos, text, 'remote')
  117. check()
  118. }
  119. const onDelete = (pos: number, text: string) => {
  120. this.cmDelete(pos, text, 'remote')
  121. check()
  122. }
  123. check()
  124. shareDoc.on('insert', onInsert)
  125. shareDoc.on('delete', onDelete)
  126. shareDoc.detach_cm6 = () => {
  127. shareDoc.removeListener('insert', onInsert)
  128. shareDoc.removeListener('delete', onDelete)
  129. delete shareDoc.detach_cm6
  130. this.shareDoc = null
  131. }
  132. }
  133. // Process an update from CodeMirror, applying changes to the
  134. // ShareJs doc if appropriate
  135. handleUpdateFromCM(transactions: readonly Transaction[]) {
  136. const shareDoc = this.shareDoc
  137. if (!shareDoc) {
  138. throw new Error('Trying to process updates with no shareDoc')
  139. }
  140. for (const transaction of transactions) {
  141. if (transaction.docChanged) {
  142. const origin = chooseOrigin(transaction)
  143. if (origin === 'remote') {
  144. return
  145. }
  146. if (
  147. this.maxDocLength &&
  148. transaction.changes.desc.newLength >= this.maxDocLength
  149. ) {
  150. shareDoc.emit(
  151. 'error',
  152. new Error('document length is greater than maxDocLength')
  153. )
  154. return
  155. }
  156. let positionShift = 0
  157. transaction.changes.iterChanges(
  158. (fromA, toA, fromB, toB, insertedText) => {
  159. const fromUndo = origin === 'undo' || origin === 'reject'
  160. const insertedLength = insertedText.length
  161. const removedLength = toA - fromA
  162. const inserted = insertedLength > 0
  163. const removed = removedLength > 0
  164. const pos = fromA + positionShift
  165. if (removed) {
  166. shareDoc.del(pos, removedLength, fromUndo)
  167. }
  168. if (inserted) {
  169. shareDoc.insert(pos, insertedText.toString(), fromUndo)
  170. }
  171. // TODO: mapPos instead?
  172. positionShift = positionShift - removedLength + insertedLength
  173. this.emit('change', this, { origin, inserted, removed })
  174. }
  175. )
  176. }
  177. }
  178. }
  179. }
  180. export const trackChangesAnnotation = Annotation.define()
  181. const chooseOrigin = (transaction: Transaction) => {
  182. if (transaction.annotation(Transaction.remote)) {
  183. return 'remote'
  184. }
  185. if (transaction.annotation(Transaction.userEvent) === 'undo') {
  186. return 'undo'
  187. }
  188. if (transaction.annotation(trackChangesAnnotation) === 'reject') {
  189. return 'reject'
  190. }
  191. }