realtime.ts 6.3 KB

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