Document.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. /* eslint-disable
  2. camelcase,
  3. n/handle-callback-err,
  4. max-len,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS001: Remove Babel/TypeScript constructor workaround
  11. * DS101: Remove unnecessary use of Array.from
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS103: Rewrite code to no longer use __guard__
  14. * DS205: Consider reworking code to avoid use of IIFEs
  15. * DS206: Consider reworking classes to avoid initClass
  16. * DS207: Consider shorter variations of null checks
  17. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  18. */
  19. import RangesTracker from '@overleaf/ranges-tracker'
  20. import EventEmitter from '../../utils/EventEmitter'
  21. import ShareJsDoc from './ShareJsDoc'
  22. import { debugConsole } from '@/utils/debugging'
  23. let Document
  24. export default Document = (function () {
  25. Document = class Document extends EventEmitter {
  26. static initClass() {
  27. this.prototype.MAX_PENDING_OP_SIZE = 64
  28. }
  29. static getDocument(ide, doc_id) {
  30. if (!this.openDocs) {
  31. this.openDocs = {}
  32. }
  33. // Try to clean up existing docs before reopening them. If the doc has no
  34. // buffered ops then it will be deleted by _cleanup() and a new instance
  35. // of the document created below. This prevents us trying to follow the
  36. // joinDoc:existing code path on an existing doc that doesn't have any
  37. // local changes and getting an error if its version is too old.
  38. if (this.openDocs[doc_id]) {
  39. debugConsole.log(
  40. `[getDocument] Cleaning up existing document instance for ${doc_id}`
  41. )
  42. this.openDocs[doc_id]._cleanUp()
  43. }
  44. if (this.openDocs[doc_id] == null) {
  45. debugConsole.log(
  46. `[getDocument] Creating new document instance for ${doc_id}`
  47. )
  48. this.openDocs[doc_id] = new Document(ide, doc_id)
  49. } else {
  50. debugConsole.log(
  51. `[getDocument] Returning existing document instance for ${doc_id}`
  52. )
  53. }
  54. return this.openDocs[doc_id]
  55. }
  56. static hasUnsavedChanges() {
  57. const object = this.openDocs || {}
  58. for (const doc_id in object) {
  59. const doc = object[doc_id]
  60. if (doc.hasBufferedOps()) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. static flushAll() {
  67. return (() => {
  68. const result = []
  69. for (const doc_id in this.openDocs) {
  70. const doc = this.openDocs[doc_id]
  71. result.push(doc.flush())
  72. }
  73. return result
  74. })()
  75. }
  76. constructor(ide, doc_id) {
  77. super()
  78. this.ide = ide
  79. this.doc_id = doc_id
  80. this.connected = this.ide.socket.socket.connected
  81. this.joined = false
  82. this.wantToBeJoined = false
  83. this._checkCM6Consistency = () => this._checkConsistency(this.cm6)
  84. this._bindToEditorEvents()
  85. this._bindToSocketEvents()
  86. }
  87. editorType() {
  88. if (this.cm6) {
  89. return 'cm6'
  90. } else {
  91. return null
  92. }
  93. }
  94. attachToCM6(cm6) {
  95. this.cm6 = cm6
  96. if (this.doc != null) {
  97. this.doc.attachToCM6(this.cm6)
  98. }
  99. if (this.cm6 != null) {
  100. this.cm6.on('change', this._checkCM6Consistency)
  101. }
  102. return this.ide.$scope.$emit('document:opened', this.doc)
  103. }
  104. detachFromCM6() {
  105. if (this.doc != null) {
  106. this.doc.detachFromCM6()
  107. }
  108. if (this.cm6 != null) {
  109. this.cm6.off('change', this._checkCM6Consistency)
  110. }
  111. delete this.cm6
  112. this.clearChaosMonkey()
  113. return this.ide.$scope.$emit('document:closed', this.doc)
  114. }
  115. submitOp(...args) {
  116. return this.doc != null
  117. ? this.doc.submitOp(...Array.from(args || []))
  118. : undefined
  119. }
  120. _checkConsistency(editor) {
  121. // We've been seeing a lot of errors when I think there shouldn't be
  122. // any, which may be related to this check happening before the change is
  123. // applied. If we use a timeout, hopefully we can reduce this.
  124. return setTimeout(() => {
  125. const editorValue = editor != null ? editor.getValue() : undefined
  126. const sharejsValue =
  127. this.doc != null ? this.doc.getSnapshot() : undefined
  128. if (editorValue !== sharejsValue) {
  129. return this._onError(
  130. new Error('Editor text does not match server text'),
  131. {},
  132. editorValue
  133. )
  134. }
  135. }, 0)
  136. }
  137. getSnapshot() {
  138. return this.doc != null ? this.doc.getSnapshot() : undefined
  139. }
  140. getType() {
  141. return this.doc != null ? this.doc.getType() : undefined
  142. }
  143. getInflightOp() {
  144. return this.doc != null ? this.doc.getInflightOp() : undefined
  145. }
  146. getPendingOp() {
  147. return this.doc != null ? this.doc.getPendingOp() : undefined
  148. }
  149. getRecentAck() {
  150. return this.doc != null ? this.doc.getRecentAck() : undefined
  151. }
  152. getOpSize(op) {
  153. return this.doc != null ? this.doc.getOpSize(op) : undefined
  154. }
  155. hasBufferedOps() {
  156. return this.doc != null ? this.doc.hasBufferedOps() : undefined
  157. }
  158. setTrackingChanges(track_changes) {
  159. return (this.doc.track_changes = track_changes)
  160. }
  161. getTrackingChanges() {
  162. return !!this.doc.track_changes
  163. }
  164. setTrackChangesIdSeeds(id_seeds) {
  165. return (this.doc.track_changes_id_seeds = id_seeds)
  166. }
  167. _bindToSocketEvents() {
  168. this._onUpdateAppliedHandler = update => this._onUpdateApplied(update)
  169. this.ide.socket.on('otUpdateApplied', this._onUpdateAppliedHandler)
  170. this._onErrorHandler = (error, message) => {
  171. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  172. // sure that message.doc_id exists.
  173. if (message.doc_id !== this.doc_id) {
  174. // This error is for another doc. Do not action it. We could open
  175. // a modal that has the wrong context on it.
  176. return
  177. }
  178. this._onError(error, message)
  179. }
  180. this.ide.socket.on('otUpdateError', this._onErrorHandler)
  181. this._onDisconnectHandler = error => this._onDisconnect(error)
  182. return this.ide.socket.on('disconnect', this._onDisconnectHandler)
  183. }
  184. _bindToEditorEvents() {
  185. const onReconnectHandler = update => {
  186. return this._onReconnect(update)
  187. }
  188. return (this._unsubscribeReconnectHandler = this.ide.$scope.$on(
  189. 'project:joined',
  190. onReconnectHandler
  191. ))
  192. }
  193. _unBindFromEditorEvents() {
  194. return this._unsubscribeReconnectHandler()
  195. }
  196. _unBindFromSocketEvents() {
  197. this.ide.socket.removeListener(
  198. 'otUpdateApplied',
  199. this._onUpdateAppliedHandler
  200. )
  201. this.ide.socket.removeListener('otUpdateError', this._onErrorHandler)
  202. return this.ide.socket.removeListener(
  203. 'disconnect',
  204. this._onDisconnectHandler
  205. )
  206. }
  207. leaveAndCleanUp(cb) {
  208. return this.leave(error => {
  209. this._cleanUp()
  210. if (cb) cb(error)
  211. })
  212. }
  213. join(callback) {
  214. if (callback == null) {
  215. callback = function () {}
  216. }
  217. this.wantToBeJoined = true
  218. this._cancelLeave()
  219. if (this.connected) {
  220. return this._joinDoc(callback)
  221. } else {
  222. if (!this._joinCallbacks) {
  223. this._joinCallbacks = []
  224. }
  225. return this._joinCallbacks.push(callback)
  226. }
  227. }
  228. leave(callback) {
  229. if (callback == null) {
  230. callback = function () {}
  231. }
  232. this.flush() // force an immediate flush when leaving document
  233. this.wantToBeJoined = false
  234. this._cancelJoin()
  235. if (this.doc != null && this.doc.hasBufferedOps()) {
  236. debugConsole.log(
  237. '[leave] Doc has buffered ops, pushing callback for later'
  238. )
  239. if (!this._leaveCallbacks) {
  240. this._leaveCallbacks = []
  241. }
  242. return this._leaveCallbacks.push(callback)
  243. } else if (!this.connected) {
  244. debugConsole.log('[leave] Not connected, returning now')
  245. return callback()
  246. } else {
  247. debugConsole.log('[leave] Leaving now')
  248. return this._leaveDoc(callback)
  249. }
  250. }
  251. flush() {
  252. return this.doc != null ? this.doc.flushPendingOps() : undefined
  253. }
  254. chaosMonkey(line, char) {
  255. if (line == null) {
  256. line = 0
  257. }
  258. if (char == null) {
  259. char = 'a'
  260. }
  261. const orig = char
  262. let copy = null
  263. let pos = 0
  264. const timer = () => {
  265. if (copy == null || !copy.length) {
  266. copy = orig.slice() + ' ' + new Date() + '\n'
  267. line += Math.random() > 0.1 ? 1 : -2
  268. if (line < 0) {
  269. line = 0
  270. }
  271. pos = 0
  272. }
  273. char = copy[0]
  274. copy = copy.slice(1)
  275. if (this.cm6) {
  276. this.cm6.view.dispatch({
  277. changes: {
  278. from: Math.min(pos, this.cm6.view.state.doc.length),
  279. insert: char,
  280. },
  281. })
  282. }
  283. pos += 1
  284. return (this._cm = setTimeout(
  285. timer,
  286. 100 + (Math.random() < 0.1 ? 1000 : 0)
  287. ))
  288. }
  289. return (this._cm = timer())
  290. }
  291. clearChaosMonkey() {
  292. const timer = this._cm
  293. if (timer) {
  294. delete this._cm
  295. return clearTimeout(timer)
  296. }
  297. }
  298. pollSavedStatus() {
  299. // returns false if doc has ops waiting to be acknowledged or
  300. // sent that haven't changed since the last time we checked.
  301. // Otherwise returns true.
  302. let saved
  303. const inflightOp = this.getInflightOp()
  304. const pendingOp = this.getPendingOp()
  305. const recentAck = this.getRecentAck()
  306. const pendingOpSize = pendingOp != null && this.getOpSize(pendingOp)
  307. if (inflightOp == null && pendingOp == null) {
  308. // there's nothing going on, this is ok.
  309. saved = true
  310. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  311. } else if (inflightOp != null && inflightOp === this.oldInflightOp) {
  312. // The same inflight op has been sitting unacked since we
  313. // last checked, this is bad.
  314. saved = false
  315. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  316. } else if (
  317. pendingOp != null &&
  318. recentAck &&
  319. pendingOpSize < this.MAX_PENDING_OP_SIZE
  320. ) {
  321. // There is an op waiting to go to server but it is small and
  322. // within the flushDelay, this is ok for now.
  323. saved = true
  324. debugConsole.log(
  325. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  326. pendingOp,
  327. pendingOpSize
  328. )
  329. } else {
  330. // In any other situation, assume the document is unsaved.
  331. saved = false
  332. debugConsole.log(
  333. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  334. inflightOp != null
  335. }, pendingOp?: ${pendingOp != null})`
  336. )
  337. }
  338. this.oldInflightOp = inflightOp
  339. return saved
  340. }
  341. _cancelLeave() {
  342. if (this._leaveCallbacks != null) {
  343. return delete this._leaveCallbacks
  344. }
  345. }
  346. _cancelJoin() {
  347. if (this._joinCallbacks != null) {
  348. return delete this._joinCallbacks
  349. }
  350. }
  351. _onUpdateApplied(update) {
  352. this.ide.pushEvent('received-update', {
  353. doc_id: this.doc_id,
  354. remote_doc_id: update != null ? update.doc : undefined,
  355. wantToBeJoined: this.wantToBeJoined,
  356. update,
  357. hasDoc: this.doc != null,
  358. })
  359. if (
  360. window.disconnectOnAck != null &&
  361. Math.random() < window.disconnectOnAck
  362. ) {
  363. debugConsole.log('Disconnecting on ack', update)
  364. window._ide.socket.socket.disconnect()
  365. // Pretend we never received the ack
  366. return
  367. }
  368. if (window.dropAcks != null && Math.random() < window.dropAcks) {
  369. if (update.op == null) {
  370. // Only drop our own acks, not collaborator updates
  371. debugConsole.log('Simulating a lost ack', update)
  372. return
  373. }
  374. }
  375. if (
  376. (update != null ? update.doc : undefined) === this.doc_id &&
  377. this.doc != null
  378. ) {
  379. this.ide.pushEvent('received-update:processing', {
  380. update,
  381. })
  382. // FIXME: change this back to processUpdateFromServer when redis fixed
  383. this.doc.processUpdateFromServerInOrder(update)
  384. if (!this.wantToBeJoined) {
  385. return this.leave()
  386. }
  387. }
  388. }
  389. _onDisconnect() {
  390. debugConsole.log('[onDisconnect] disconnecting')
  391. this.connected = false
  392. this.joined = false
  393. return this.doc != null
  394. ? this.doc.updateConnectionState('disconnected')
  395. : undefined
  396. }
  397. _onReconnect() {
  398. debugConsole.log('[onReconnect] reconnected (joined project)')
  399. this.ide.pushEvent('reconnected:afterJoinProject')
  400. this.connected = true
  401. if (
  402. this.wantToBeJoined ||
  403. (this.doc != null ? this.doc.hasBufferedOps() : undefined)
  404. ) {
  405. debugConsole.log(
  406. `[onReconnect] Rejoining (wantToBeJoined: ${
  407. this.wantToBeJoined
  408. } OR hasBufferedOps: ${
  409. this.doc != null ? this.doc.hasBufferedOps() : undefined
  410. })`
  411. )
  412. return this._joinDoc(error => {
  413. if (error != null) {
  414. return this._onError(error)
  415. }
  416. this.doc.updateConnectionState('ok')
  417. this.doc.flushPendingOps()
  418. return this._callJoinCallbacks()
  419. })
  420. }
  421. }
  422. _callJoinCallbacks() {
  423. for (const callback of Array.from(this._joinCallbacks || [])) {
  424. callback()
  425. }
  426. return delete this._joinCallbacks
  427. }
  428. _joinDoc(callback) {
  429. if (callback == null) {
  430. callback = function () {}
  431. }
  432. if (this.doc != null) {
  433. this.ide.pushEvent('joinDoc:existing', {
  434. doc_id: this.doc_id,
  435. version: this.doc.getVersion(),
  436. })
  437. return this.ide.socket.emit(
  438. 'joinDoc',
  439. this.doc_id,
  440. this.doc.getVersion(),
  441. { encodeRanges: true },
  442. (error, docLines, version, updates, ranges) => {
  443. if (error != null) {
  444. return callback(error)
  445. }
  446. this.joined = true
  447. this.doc.catchUp(updates)
  448. this._decodeRanges(ranges)
  449. this._catchUpRanges(
  450. ranges != null ? ranges.changes : undefined,
  451. ranges != null ? ranges.comments : undefined
  452. )
  453. return callback()
  454. }
  455. )
  456. } else {
  457. this.ide.pushEvent('joinDoc:new', {
  458. doc_id: this.doc_id,
  459. })
  460. return this.ide.socket.emit(
  461. 'joinDoc',
  462. this.doc_id,
  463. { encodeRanges: true },
  464. (error, docLines, version, updates, ranges) => {
  465. if (error != null) {
  466. return callback(error)
  467. }
  468. this.joined = true
  469. this.ide.pushEvent('joinDoc:inited', {
  470. doc_id: this.doc_id,
  471. version,
  472. })
  473. this.doc = new ShareJsDoc(
  474. this.doc_id,
  475. docLines,
  476. version,
  477. this.ide.socket,
  478. this.ide.globalEditorWatchdogManager
  479. )
  480. this._decodeRanges(ranges)
  481. this.ranges = new RangesTracker(
  482. ranges != null ? ranges.changes : undefined,
  483. ranges != null ? ranges.comments : undefined
  484. )
  485. this._bindToShareJsDocEvents()
  486. return callback()
  487. }
  488. )
  489. }
  490. }
  491. _decodeRanges(ranges) {
  492. const decodeFromWebsockets = text => decodeURIComponent(escape(text))
  493. try {
  494. for (const change of Array.from(ranges.changes || [])) {
  495. if (change.op.i != null) {
  496. change.op.i = decodeFromWebsockets(change.op.i)
  497. }
  498. if (change.op.d != null) {
  499. change.op.d = decodeFromWebsockets(change.op.d)
  500. }
  501. }
  502. return (() => {
  503. const result = []
  504. for (const comment of Array.from(ranges.comments || [])) {
  505. if (comment.op.c != null) {
  506. result.push((comment.op.c = decodeFromWebsockets(comment.op.c)))
  507. } else {
  508. result.push(undefined)
  509. }
  510. }
  511. return result
  512. })()
  513. } catch (err) {
  514. debugConsole.error(err)
  515. }
  516. }
  517. _leaveDoc(callback) {
  518. if (callback == null) {
  519. callback = function () {}
  520. }
  521. this.ide.pushEvent('leaveDoc', {
  522. doc_id: this.doc_id,
  523. })
  524. debugConsole.log('[_leaveDoc] Sending leaveDoc request')
  525. return this.ide.socket.emit('leaveDoc', this.doc_id, error => {
  526. if (error != null) {
  527. return callback(error)
  528. }
  529. this.joined = false
  530. for (callback of Array.from(this._leaveCallbacks || [])) {
  531. debugConsole.log('[_leaveDoc] Calling buffered callback', callback)
  532. callback(error)
  533. }
  534. delete this._leaveCallbacks
  535. return callback(error)
  536. })
  537. }
  538. _cleanUp() {
  539. // if we arrive here from _onError the pending and inflight ops will have been cleared
  540. if (this.hasBufferedOps()) {
  541. debugConsole.log(
  542. `[_cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  543. )
  544. return // return immediately, do not unbind from events
  545. } else if (Document.openDocs[this.doc_id] === this) {
  546. debugConsole.log(
  547. `[_cleanUp] Removing self (${this.doc_id}) from in openDocs`
  548. )
  549. delete Document.openDocs[this.doc_id]
  550. } else {
  551. // It's possible that this instance has error, and the doc has been reloaded.
  552. // This creates a new instance in Document.openDoc with the same id. We shouldn't
  553. // clear it because it's not this instance.
  554. debugConsole.log(
  555. `[_cleanUp] New instance of (${this.doc_id}) created. Not removing`
  556. )
  557. }
  558. this._unBindFromEditorEvents()
  559. return this._unBindFromSocketEvents()
  560. }
  561. _bindToShareJsDocEvents() {
  562. this.doc.on('error', (error, meta) => this._onError(error, meta))
  563. this.doc.on('externalUpdate', update => {
  564. this.ide.pushEvent('externalUpdate', { doc_id: this.doc_id })
  565. return this.trigger('externalUpdate', update)
  566. })
  567. this.doc.on('remoteop', (...args) => {
  568. this.ide.pushEvent('remoteop', { doc_id: this.doc_id })
  569. return this.trigger('remoteop', ...Array.from(args))
  570. })
  571. this.doc.on('op:sent', op => {
  572. this.ide.pushEvent('op:sent', {
  573. doc_id: this.doc_id,
  574. op,
  575. })
  576. return this.trigger('op:sent')
  577. })
  578. this.doc.on('op:acknowledged', op => {
  579. this.ide.pushEvent('op:acknowledged', {
  580. doc_id: this.doc_id,
  581. op,
  582. })
  583. this.ide.$scope.$emit('ide:opAcknowledged', {
  584. doc_id: this.doc_id,
  585. op,
  586. })
  587. return this.trigger('op:acknowledged')
  588. })
  589. this.doc.on('op:timeout', op => {
  590. this.ide.pushEvent('op:timeout', {
  591. doc_id: this.doc_id,
  592. op,
  593. })
  594. this.trigger('op:timeout')
  595. return this._onError(new Error('op timed out'))
  596. })
  597. this.doc.on('flush', (inflightOp, pendingOp, version) => {
  598. return this.ide.pushEvent('flush', {
  599. doc_id: this.doc_id,
  600. inflightOp,
  601. pendingOp,
  602. v: version,
  603. })
  604. })
  605. let docChangedTimeout
  606. this.doc.on('change', (ops, oldSnapshot, msg) => {
  607. this._applyOpsToRanges(ops, oldSnapshot, msg)
  608. if (docChangedTimeout) {
  609. window.clearTimeout(docChangedTimeout)
  610. }
  611. docChangedTimeout = window.setTimeout(() => {
  612. window.dispatchEvent(
  613. new CustomEvent('doc:changed', { detail: { id: this.doc_id } })
  614. )
  615. this.ide.$scope.$emit('doc:changed', { doc_id: this.doc_id })
  616. }, 50)
  617. })
  618. this.doc.on('flipped_pending_to_inflight', () => {
  619. return this.trigger('flipped_pending_to_inflight')
  620. })
  621. let docSavedTimeout
  622. this.doc.on('saved', () => {
  623. if (docSavedTimeout) {
  624. window.clearTimeout(docSavedTimeout)
  625. }
  626. docSavedTimeout = window.setTimeout(() => {
  627. window.dispatchEvent(
  628. new CustomEvent('doc:saved', { detail: { id: this.doc_id } })
  629. )
  630. this.ide.$scope.$emit('doc:saved', { doc_id: this.doc_id })
  631. }, 50)
  632. })
  633. }
  634. _onError(error, meta, editorContent) {
  635. if (meta == null) {
  636. meta = {}
  637. }
  638. meta.doc_id = this.doc_id
  639. debugConsole.log('ShareJS error', error, meta)
  640. if (error.message === 'no project_id found on client') {
  641. debugConsole.log('ignoring error, will wait to join project')
  642. return
  643. }
  644. if (this.doc != null) {
  645. this.doc.clearInflightAndPendingOps()
  646. }
  647. this.trigger('error', error, meta, editorContent)
  648. // The clean up should run after the error is triggered because the error triggers a
  649. // disconnect. If we run the clean up first, we remove our event handlers and miss
  650. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  651. // This could intefere with the new connection of a new instance of this document.
  652. return this._cleanUp()
  653. }
  654. _applyOpsToRanges(ops, oldSnapshot, msg) {
  655. let old_id_seed
  656. if (ops == null) {
  657. ops = []
  658. }
  659. let track_changes_as = null
  660. const remote_op = msg != null
  661. if (__guard__(msg != null ? msg.meta : undefined, x => x.tc) != null) {
  662. old_id_seed = this.ranges.getIdSeed()
  663. this.ranges.setIdSeed(msg.meta.tc)
  664. }
  665. if (remote_op && (msg.meta != null ? msg.meta.tc : undefined)) {
  666. track_changes_as = msg.meta.user_id
  667. } else if (!remote_op && this.track_changes_as != null) {
  668. ;({ track_changes_as } = this)
  669. }
  670. this.ranges.track_changes = track_changes_as != null
  671. for (const op of this._filterOps(ops)) {
  672. this.ranges.applyOp(op, { user_id: track_changes_as })
  673. }
  674. if (old_id_seed != null) {
  675. this.ranges.setIdSeed(old_id_seed)
  676. }
  677. if (remote_op) {
  678. // With remote ops, the editor hasn't been updated when we receive this op,
  679. // so defer updating track changes until it has
  680. return setTimeout(() => this.emit('ranges:dirty'))
  681. } else {
  682. return this.emit('ranges:dirty')
  683. }
  684. }
  685. _catchUpRanges(changes, comments) {
  686. // We've just been given the current server's ranges, but need to apply any local ops we have.
  687. // Reset to the server state then apply our local ops again.
  688. if (changes == null) {
  689. changes = []
  690. }
  691. if (comments == null) {
  692. comments = []
  693. }
  694. this.emit('ranges:clear')
  695. this.ranges.changes = changes
  696. this.ranges.comments = comments
  697. this.ranges.track_changes = this.doc.track_changes
  698. for (const op of this._filterOps(this.doc.getInflightOp() || [])) {
  699. this.ranges.setIdSeed(this.doc.track_changes_id_seeds.inflight)
  700. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  701. }
  702. for (const op of this._filterOps(this.doc.getPendingOp() || [])) {
  703. this.ranges.setIdSeed(this.doc.track_changes_id_seeds.pending)
  704. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  705. }
  706. return this.emit('ranges:redraw')
  707. }
  708. _filterOps(ops) {
  709. // Read-only token users can't see/edit comment, so we filter out comment
  710. // ops to avoid highlighting comment ranges.
  711. if (window.isRestrictedTokenMember) {
  712. return ops.filter(op => op.c == null)
  713. } else {
  714. return ops
  715. }
  716. }
  717. }
  718. Document.initClass()
  719. return Document
  720. })()
  721. function __guard__(value, transform) {
  722. return typeof value !== 'undefined' && value !== null
  723. ? transform(value)
  724. : undefined
  725. }