realtime.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import {
  2. Prec,
  3. Transaction,
  4. Annotation,
  5. ChangeSpec,
  6. Text,
  7. } from '@codemirror/state'
  8. import { EditorView, ViewPlugin } from '@codemirror/view'
  9. import { EventEmitter } from 'events'
  10. import RangesTracker from '@overleaf/ranges-tracker'
  11. import {
  12. ShareDoc,
  13. ShareLatexOTShareDoc,
  14. HistoryOTShareDoc,
  15. } from '../../../../../types/share-doc'
  16. import { debugConsole } from '@/utils/debugging'
  17. import { DocumentContainer } from '@/features/ide-react/editor/document-container'
  18. import { TrackedChangeList } from 'overleaf-editor-core'
  19. import {
  20. updateTrackedChanges,
  21. setTrackChangesUserId,
  22. historyOTOperationEffect,
  23. } from './history-ot'
  24. /*
  25. * Integrate CodeMirror 6 with the real-time system, via ShareJS.
  26. *
  27. * Changes from CodeMirror are passed to the shareDoc
  28. * via `handleTransaction`, while changes arriving from
  29. * real-time are passed to CodeMirror via the EditorFacade.
  30. *
  31. * We use an `EditorFacade` to integrate with the rest of
  32. * the IDE, providing an interface the other systems can work with.
  33. *
  34. * Related files:
  35. * - frontend/js/ide/editor/Document.js
  36. * - frontend/js/ide/editor/ShareJsDoc.js
  37. * - frontend/js/ide/connection/EditorWatchdogManager.js
  38. * - frontend/js/features/ide-react/editor/document.ts
  39. * - frontend/js/features/ide-react/editor/share-js-doc.ts
  40. * - frontend/js/features/ide-react/connection/editor-watchdog-manager.js
  41. */
  42. type Origin = 'remote' | 'undo' | 'reject' | undefined
  43. export type ChangeDescription = {
  44. origin: Origin
  45. inserted: boolean
  46. removed: boolean
  47. }
  48. /**
  49. * A custom extension that connects the CodeMirror 6 editor to the currently open ShareJS document.
  50. */
  51. export const realtime = (
  52. { currentDoc }: { currentDoc: DocumentContainer },
  53. handleError: (error: Error) => void
  54. ) => {
  55. const realtimePlugin = ViewPlugin.define(view => {
  56. const editor = new EditorFacade(view)
  57. currentDoc.attachToCM6(editor)
  58. return {
  59. update(update) {
  60. if (update.docChanged) {
  61. editor.handleUpdateFromCM(update.transactions, currentDoc.ranges)
  62. }
  63. },
  64. destroy() {
  65. // TODO: wrap in a timeout so processing can finish?
  66. // window.setTimeout(() => {
  67. currentDoc.detachFromCM6()
  68. // }, 0)
  69. },
  70. }
  71. })
  72. // NOTE: not a view plugin, so shouldn't get removed
  73. const ensureRealtimePlugin = EditorView.updateListener.of(update => {
  74. if (!update.view.plugin(realtimePlugin)) {
  75. const message = 'The realtime extension has been destroyed!!'
  76. debugConsole.warn(message)
  77. if (currentDoc.doc) {
  78. // display the "out of sync" modal
  79. currentDoc.doc.emit('error', message)
  80. } else {
  81. // display the error boundary
  82. handleError(new Error(message))
  83. }
  84. }
  85. })
  86. return Prec.highest([realtimePlugin, ensureRealtimePlugin])
  87. }
  88. type OTAdapter = {
  89. handleUpdateFromCM(
  90. transactions: readonly Transaction[],
  91. ranges?: RangesTracker
  92. ): void
  93. attachShareJs(): void
  94. }
  95. export class EditorFacade extends EventEmitter {
  96. private otAdapter: OTAdapter | null
  97. public events: EventEmitter
  98. constructor(public view: EditorView) {
  99. super()
  100. this.view = view
  101. this.otAdapter = null
  102. this.events = new EventEmitter()
  103. }
  104. getValue() {
  105. return this.view.state.doc.toString()
  106. }
  107. // Dispatch changes to CodeMirror view
  108. cmChange(changes: ChangeSpec, origin?: string) {
  109. const isRemote = origin === 'remote'
  110. this.view.dispatch({
  111. changes,
  112. annotations: [
  113. Transaction.remote.of(isRemote),
  114. Transaction.addToHistory.of(!isRemote),
  115. ],
  116. effects:
  117. // if this is a remote change, restore a snapshot of the current scroll position after the change has been applied
  118. isRemote
  119. ? this.view.scrollSnapshot().map(this.view.state.changes(changes))
  120. : undefined,
  121. })
  122. }
  123. cmInsert(position: number, text: string, origin?: string) {
  124. this.cmChange({ from: position, insert: text }, origin)
  125. }
  126. cmDelete(position: number, text: string, origin?: string) {
  127. this.cmChange({ from: position, to: position + text.length }, origin)
  128. }
  129. cmUpdateTrackedChanges(trackedChanges: TrackedChangeList) {
  130. this.view.dispatch(updateTrackedChanges(trackedChanges))
  131. }
  132. attachShareJs(shareDoc: ShareDoc, maxDocLength?: number) {
  133. this.otAdapter =
  134. shareDoc.otType === 'history-ot'
  135. ? new HistoryOTAdapter(this, shareDoc, maxDocLength)
  136. : new ShareLatexOTAdapter(this, shareDoc, maxDocLength)
  137. this.otAdapter.attachShareJs()
  138. }
  139. detachShareJs() {
  140. this.otAdapter = null
  141. }
  142. handleUpdateFromCM(
  143. transactions: readonly Transaction[],
  144. ranges?: RangesTracker
  145. ) {
  146. if (this.otAdapter == null) {
  147. throw new Error('Trying to process updates with no otAdapter')
  148. }
  149. this.otAdapter.handleUpdateFromCM(transactions, ranges)
  150. }
  151. setTrackChangesUserId(userId: string | null) {
  152. if (this.otAdapter instanceof HistoryOTAdapter) {
  153. this.view.dispatch(setTrackChangesUserId(userId))
  154. }
  155. }
  156. }
  157. class ShareLatexOTAdapter {
  158. constructor(
  159. public editor: EditorFacade,
  160. private shareDoc: ShareLatexOTShareDoc,
  161. private maxDocLength?: number
  162. ) {
  163. this.editor = editor
  164. this.shareDoc = shareDoc
  165. this.maxDocLength = maxDocLength
  166. }
  167. // Connect to ShareJS, passing changes to the CodeMirror view
  168. // as new transactions.
  169. // This is a broad immitation of helper functions supplied in
  170. // the sharejs library. (See vendor/libs/sharejs, in particular
  171. // the 'attach_ace' helper)
  172. attachShareJs() {
  173. const shareDoc = this.shareDoc
  174. const check = () => {
  175. // run in a timeout so it checks the editor content once this update has been applied
  176. window.setTimeout(() => {
  177. const editorText = this.editor.getValue()
  178. const otText = shareDoc.getText()
  179. if (editorText !== otText) {
  180. this.shareDoc.emit('error', 'Text does not match in CodeMirror 6')
  181. debugConsole.error('Text does not match!')
  182. debugConsole.error('editor: ' + editorText)
  183. debugConsole.error('ot: ' + otText)
  184. }
  185. }, 0)
  186. }
  187. const onInsert = (pos: number, text: string) => {
  188. this.editor.cmInsert(pos, text, 'remote')
  189. check()
  190. }
  191. const onDelete = (pos: number, text: string) => {
  192. this.editor.cmDelete(pos, text, 'remote')
  193. check()
  194. }
  195. check()
  196. shareDoc.on('insert', onInsert)
  197. shareDoc.on('delete', onDelete)
  198. shareDoc.detach_cm6 = () => {
  199. shareDoc.removeListener('insert', onInsert)
  200. shareDoc.removeListener('delete', onDelete)
  201. delete shareDoc.detach_cm6
  202. this.editor.detachShareJs()
  203. }
  204. }
  205. // Process an update from CodeMirror, applying changes to the
  206. // ShareJs doc if appropriate
  207. handleUpdateFromCM(
  208. transactions: readonly Transaction[],
  209. ranges?: RangesTracker
  210. ) {
  211. const shareDoc = this.shareDoc
  212. const trackedDeletesLength =
  213. ranges != null ? ranges.getTrackedDeletesLength() : 0
  214. for (const transaction of transactions) {
  215. if (transaction.docChanged) {
  216. const origin = chooseOrigin(transaction)
  217. if (origin === 'remote') {
  218. return
  219. }
  220. // This is an approximation. Some deletes could have generated new
  221. // tracked deletes since we measured trackedDeletesLength at the top of
  222. // the function. Unfortunately, the ranges tracker is only updated
  223. // after all transactions are processed, so it's not easy to get an
  224. // exact number.
  225. const fullDocLength =
  226. transaction.changes.desc.newLength + trackedDeletesLength
  227. if (this.maxDocLength && fullDocLength >= this.maxDocLength) {
  228. shareDoc.emit(
  229. 'error',
  230. new Error('document length is greater than maxDocLength')
  231. )
  232. return
  233. }
  234. let positionShift = 0
  235. transaction.changes.iterChanges(
  236. (fromA, toA, fromB, toB, insertedText) => {
  237. const fromUndo = origin === 'undo' || origin === 'reject'
  238. const insertedLength = insertedText.length
  239. const removedLength = toA - fromA
  240. const inserted = insertedLength > 0
  241. const removed = removedLength > 0
  242. const pos = fromA + positionShift
  243. if (removed) {
  244. shareDoc.del(pos, removedLength, fromUndo)
  245. }
  246. if (inserted) {
  247. shareDoc.insert(pos, insertedText.toString(), fromUndo)
  248. }
  249. // TODO: mapPos instead?
  250. positionShift = positionShift - removedLength + insertedLength
  251. const changeDescription: ChangeDescription = {
  252. origin,
  253. inserted,
  254. removed,
  255. }
  256. this.editor.emit('change', this.editor, changeDescription)
  257. }
  258. )
  259. }
  260. }
  261. }
  262. }
  263. class HistoryOTAdapter {
  264. constructor(
  265. public editor: EditorFacade,
  266. private shareDoc: HistoryOTShareDoc,
  267. private maxDocLength?: number
  268. ) {
  269. this.editor = editor
  270. this.shareDoc = shareDoc
  271. this.maxDocLength = maxDocLength
  272. }
  273. attachShareJs() {
  274. this.checkContent()
  275. const onInsert = this.onShareJsInsert.bind(this)
  276. const onDelete = this.onShareJsDelete.bind(this)
  277. const onTrackedChangesInvalidated =
  278. this.onShareJsTrackedChangesInvalidated.bind(this)
  279. this.shareDoc.on('insert', onInsert)
  280. this.shareDoc.on('delete', onDelete)
  281. this.shareDoc.on('tracked-changes-invalidated', onTrackedChangesInvalidated)
  282. this.shareDoc.detach_cm6 = () => {
  283. this.shareDoc.removeListener('insert', onInsert)
  284. this.shareDoc.removeListener('delete', onDelete)
  285. this.shareDoc.removeListener(
  286. 'tracked-changes-invalidated',
  287. onTrackedChangesInvalidated
  288. )
  289. delete this.shareDoc.detach_cm6
  290. this.editor.detachShareJs()
  291. }
  292. }
  293. handleUpdateFromCM(
  294. transactions: readonly Transaction[],
  295. ranges?: RangesTracker
  296. ) {
  297. for (const transaction of transactions) {
  298. if (
  299. this.maxDocLength &&
  300. transaction.changes.newLength >= this.maxDocLength
  301. ) {
  302. this.shareDoc.emit(
  303. 'error',
  304. new Error('document length is greater than maxDocLength')
  305. )
  306. return
  307. }
  308. let snapshotUpdated = false
  309. for (const effect of transaction.effects) {
  310. if (effect.is(historyOTOperationEffect)) {
  311. this.shareDoc.submitOp(effect.value.map(op => op.toJSON()))
  312. snapshotUpdated = true
  313. }
  314. }
  315. if (snapshotUpdated || transaction.annotation(Transaction.remote)) {
  316. window.setTimeout(() => {
  317. this.editor.cmUpdateTrackedChanges(
  318. this.shareDoc.snapshot.getTrackedChanges()
  319. )
  320. }, 0)
  321. }
  322. const origin = chooseOrigin(transaction)
  323. transaction.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
  324. this.onCodeMirrorChange(fromA, toA, fromB, toB, inserted, origin)
  325. })
  326. }
  327. }
  328. onShareJsInsert(pos: number, text: string) {
  329. this.editor.cmInsert(pos, text, 'remote')
  330. this.checkContent()
  331. }
  332. onShareJsDelete(pos: number, text: string) {
  333. this.editor.cmDelete(pos, text, 'remote')
  334. this.checkContent()
  335. }
  336. onShareJsTrackedChangesInvalidated() {
  337. this.editor.cmUpdateTrackedChanges(
  338. this.shareDoc.snapshot.getTrackedChanges()
  339. )
  340. }
  341. onCodeMirrorChange(
  342. fromA: number,
  343. toA: number,
  344. fromB: number,
  345. toB: number,
  346. insertedText: Text,
  347. origin: Origin
  348. ) {
  349. const insertedLength = insertedText.length
  350. const removedLength = toA - fromA
  351. const inserted = insertedLength > 0
  352. const removed = removedLength > 0
  353. const changeDescription: ChangeDescription = {
  354. origin,
  355. inserted,
  356. removed,
  357. }
  358. this.editor.emit('change', this.editor, changeDescription)
  359. }
  360. checkContent() {
  361. // run in a timeout so it checks the editor content once this update has been applied
  362. window.setTimeout(() => {
  363. const editorText = this.editor.getValue()
  364. const otText = this.shareDoc.getText()
  365. if (editorText !== otText) {
  366. this.shareDoc.emit('error', 'Text does not match in CodeMirror 6')
  367. debugConsole.error('Text does not match!')
  368. debugConsole.error('editor: ' + editorText)
  369. debugConsole.error('ot: ' + otText)
  370. }
  371. }, 0)
  372. }
  373. }
  374. export const trackChangesAnnotation = Annotation.define()
  375. const chooseOrigin = (transaction: Transaction) => {
  376. if (transaction.annotation(Transaction.remote)) {
  377. return 'remote'
  378. }
  379. if (transaction.annotation(Transaction.userEvent) === 'undo') {
  380. return 'undo'
  381. }
  382. if (transaction.annotation(trackChangesAnnotation) === 'reject') {
  383. return 'reject'
  384. }
  385. }