realtime.ts 7.1 KB

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