Document.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. /* eslint-disable
  2. camelcase,
  3. node/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 EventEmitter from '../../utils/EventEmitter'
  20. import ShareJsDoc from './ShareJsDoc'
  21. import RangesTracker from '../review-panel/RangesTracker'
  22. let Document
  23. export default Document = (function () {
  24. Document = class Document extends EventEmitter {
  25. static initClass() {
  26. this.prototype.MAX_PENDING_OP_SIZE = 64
  27. }
  28. static getDocument(ide, doc_id) {
  29. if (!this.openDocs) {
  30. this.openDocs = {}
  31. }
  32. // Try to clean up existing docs before reopening them. If the doc has no
  33. // buffered ops then it will be deleted by _cleanup() and a new instance
  34. // of the document created below. This prevents us trying to follow the
  35. // joinDoc:existing code path on an existing doc that doesn't have any
  36. // local changes and getting an error if its version is too old.
  37. if (this.openDocs[doc_id]) {
  38. sl_console.log(
  39. `[getDocument] Cleaning up existing document instance for ${doc_id}`
  40. )
  41. this.openDocs[doc_id]._cleanUp()
  42. }
  43. if (this.openDocs[doc_id] == null) {
  44. sl_console.log(
  45. `[getDocument] Creating new document instance for ${doc_id}`
  46. )
  47. this.openDocs[doc_id] = new Document(ide, doc_id)
  48. } else {
  49. sl_console.log(
  50. `[getDocument] Returning existing document instance for ${doc_id}`
  51. )
  52. }
  53. return this.openDocs[doc_id]
  54. }
  55. static hasUnsavedChanges() {
  56. const object = this.openDocs || {}
  57. for (let doc_id in object) {
  58. const doc = object[doc_id]
  59. if (doc.hasBufferedOps()) {
  60. return true
  61. }
  62. }
  63. return false
  64. }
  65. static flushAll() {
  66. return (() => {
  67. const result = []
  68. for (let doc_id in this.openDocs) {
  69. const doc = this.openDocs[doc_id]
  70. result.push(doc.flush())
  71. }
  72. return result
  73. })()
  74. }
  75. constructor(ide, doc_id) {
  76. super()
  77. this.ide = ide
  78. this.doc_id = doc_id
  79. this.connected = this.ide.socket.socket.connected
  80. this.joined = false
  81. this.wantToBeJoined = false
  82. this._checkAceConsistency = () => this._checkConsistency(this.ace)
  83. this._checkCMConsistency = () => this._checkConsistency(this.cm)
  84. this._bindToEditorEvents()
  85. this._bindToSocketEvents()
  86. }
  87. attachToAce(ace) {
  88. this.ace = ace
  89. if (this.doc != null) {
  90. this.doc.attachToAce(this.ace)
  91. }
  92. const editorDoc = this.ace.getSession().getDocument()
  93. editorDoc.on('change', this._checkAceConsistency)
  94. return this.ide.$scope.$emit('document:opened', this.doc)
  95. }
  96. detachFromAce() {
  97. if (this.doc != null) {
  98. this.doc.detachFromAce()
  99. }
  100. const editorDoc =
  101. this.ace != null ? this.ace.getSession().getDocument() : undefined
  102. if (editorDoc != null) {
  103. editorDoc.off('change', this._checkAceConsistency)
  104. }
  105. return this.ide.$scope.$emit('document:closed', this.doc)
  106. }
  107. attachToCM(cm) {
  108. this.cm = cm
  109. if (this.doc != null) {
  110. this.doc.attachToCM(this.cm)
  111. }
  112. if (this.cm != null) {
  113. this.cm.on('change', this._checkCMConsistency)
  114. }
  115. return this.ide.$scope.$emit('document:opened', this.doc)
  116. }
  117. detachFromCM() {
  118. if (this.doc != null) {
  119. this.doc.detachFromCM()
  120. }
  121. if (this.cm != null) {
  122. this.cm.off('change', this._checkCMConsistency)
  123. }
  124. return this.ide.$scope.$emit('document:closed', this.doc)
  125. }
  126. submitOp(...args) {
  127. return this.doc != null
  128. ? this.doc.submitOp(...Array.from(args || []))
  129. : undefined
  130. }
  131. _checkConsistency(editor) {
  132. // We've been seeing a lot of errors when I think there shouldn't be
  133. // any, which may be related to this check happening before the change is
  134. // applied. If we use a timeout, hopefully we can reduce this.
  135. return setTimeout(() => {
  136. const editorValue = editor != null ? editor.getValue() : undefined
  137. const sharejsValue =
  138. this.doc != null ? this.doc.getSnapshot() : undefined
  139. if (editorValue !== sharejsValue) {
  140. return this._onError(
  141. new Error('Editor text does not match server text'),
  142. {},
  143. editorValue
  144. )
  145. }
  146. }, 0)
  147. }
  148. getSnapshot() {
  149. return this.doc != null ? this.doc.getSnapshot() : undefined
  150. }
  151. getType() {
  152. return this.doc != null ? this.doc.getType() : undefined
  153. }
  154. getInflightOp() {
  155. return this.doc != null ? this.doc.getInflightOp() : undefined
  156. }
  157. getPendingOp() {
  158. return this.doc != null ? this.doc.getPendingOp() : undefined
  159. }
  160. getRecentAck() {
  161. return this.doc != null ? this.doc.getRecentAck() : undefined
  162. }
  163. getOpSize(op) {
  164. return this.doc != null ? this.doc.getOpSize(op) : undefined
  165. }
  166. hasBufferedOps() {
  167. return this.doc != null ? this.doc.hasBufferedOps() : undefined
  168. }
  169. setTrackingChanges(track_changes) {
  170. return (this.doc.track_changes = track_changes)
  171. }
  172. getTrackingChanges() {
  173. return !!this.doc.track_changes
  174. }
  175. setTrackChangesIdSeeds(id_seeds) {
  176. return (this.doc.track_changes_id_seeds = id_seeds)
  177. }
  178. _bindToSocketEvents() {
  179. this._onUpdateAppliedHandler = update => this._onUpdateApplied(update)
  180. this.ide.socket.on('otUpdateApplied', this._onUpdateAppliedHandler)
  181. this._onErrorHandler = (error, message) => {
  182. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  183. // sure that message.doc_id exists.
  184. if (message.doc_id !== this.doc_id) {
  185. // This error is for another doc. Do not action it. We could open
  186. // a modal that has the wrong context on it.
  187. return
  188. }
  189. this._onError(error, message)
  190. }
  191. this.ide.socket.on('otUpdateError', this._onErrorHandler)
  192. this._onDisconnectHandler = error => this._onDisconnect(error)
  193. return this.ide.socket.on('disconnect', this._onDisconnectHandler)
  194. }
  195. _bindToEditorEvents() {
  196. const onReconnectHandler = update => {
  197. return this._onReconnect(update)
  198. }
  199. return (this._unsubscribeReconnectHandler = this.ide.$scope.$on(
  200. 'project:joined',
  201. onReconnectHandler
  202. ))
  203. }
  204. _unBindFromEditorEvents() {
  205. return this._unsubscribeReconnectHandler()
  206. }
  207. _unBindFromSocketEvents() {
  208. this.ide.socket.removeListener(
  209. 'otUpdateApplied',
  210. this._onUpdateAppliedHandler
  211. )
  212. this.ide.socket.removeListener('otUpdateError', this._onErrorHandler)
  213. return this.ide.socket.removeListener(
  214. 'disconnect',
  215. this._onDisconnectHandler
  216. )
  217. }
  218. leaveAndCleanUp(cb) {
  219. return this.leave(error => {
  220. this._cleanUp()
  221. if (cb) cb(error)
  222. })
  223. }
  224. join(callback) {
  225. if (callback == null) {
  226. callback = function (error) {}
  227. }
  228. this.wantToBeJoined = true
  229. this._cancelLeave()
  230. if (this.connected) {
  231. return this._joinDoc(callback)
  232. } else {
  233. if (!this._joinCallbacks) {
  234. this._joinCallbacks = []
  235. }
  236. return this._joinCallbacks.push(callback)
  237. }
  238. }
  239. leave(callback) {
  240. if (callback == null) {
  241. callback = function (error) {}
  242. }
  243. this.flush() // force an immediate flush when leaving document
  244. this.wantToBeJoined = false
  245. this._cancelJoin()
  246. if (this.doc != null && this.doc.hasBufferedOps()) {
  247. sl_console.log(
  248. '[leave] Doc has buffered ops, pushing callback for later'
  249. )
  250. if (!this._leaveCallbacks) {
  251. this._leaveCallbacks = []
  252. }
  253. return this._leaveCallbacks.push(callback)
  254. } else if (!this.connected) {
  255. sl_console.log('[leave] Not connected, returning now')
  256. return callback()
  257. } else {
  258. sl_console.log('[leave] Leaving now')
  259. return this._leaveDoc(callback)
  260. }
  261. }
  262. flush() {
  263. return this.doc != null ? this.doc.flushPendingOps() : undefined
  264. }
  265. chaosMonkey(line, char) {
  266. if (line == null) {
  267. line = 0
  268. }
  269. if (char == null) {
  270. char = 'a'
  271. }
  272. const orig = char
  273. let copy = null
  274. let pos = 0
  275. var timer = () => {
  276. if (copy == null || !copy.length) {
  277. copy = orig.slice() + ' ' + new Date() + '\n'
  278. line += Math.random() > 0.1 ? 1 : -2
  279. if (line < 0) {
  280. line = 0
  281. }
  282. pos = 0
  283. }
  284. char = copy[0]
  285. copy = copy.slice(1)
  286. this.ace.session.insert({ row: line, column: pos }, char)
  287. pos += 1
  288. return (this._cm = setTimeout(
  289. timer,
  290. 100 + (Math.random() < 0.1 ? 1000 : 0)
  291. ))
  292. }
  293. return (this._cm = timer())
  294. }
  295. clearChaosMonkey() {
  296. return clearTimeout(this._cm) // pending ops bigger than this are always considered unsaved
  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. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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 (let 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 (error) {}
  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 (let 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 (let 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. return console.log(err)
  515. }
  516. }
  517. _leaveDoc(callback) {
  518. if (callback == null) {
  519. callback = function (error) {}
  520. }
  521. this.ide.pushEvent('leaveDoc', {
  522. doc_id: this.doc_id,
  523. })
  524. sl_console.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. sl_console.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. sl_console.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. sl_console.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. sl_console.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'), { op })
  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. this.doc.on('change', (ops, oldSnapshot, msg) => {
  606. this._applyOpsToRanges(ops, oldSnapshot, msg)
  607. return this.ide.$scope.$emit('doc:changed', { doc_id: this.doc_id })
  608. })
  609. this.doc.on('flipped_pending_to_inflight', () => {
  610. return this.trigger('flipped_pending_to_inflight')
  611. })
  612. return this.doc.on('saved', () => {
  613. return this.ide.$scope.$emit('doc:saved', { doc_id: this.doc_id })
  614. })
  615. }
  616. _onError(error, meta, editorContent) {
  617. if (meta == null) {
  618. meta = {}
  619. }
  620. meta.doc_id = this.doc_id
  621. sl_console.log('ShareJS error', error, meta)
  622. if (error.message === 'no project_id found on client') {
  623. sl_console.log('ignoring error, will wait to join project')
  624. return
  625. }
  626. if (typeof ga === 'function') {
  627. // sanitise the error message before sending (the "delete component"
  628. // error in public/js/libs/sharejs.js includes the some document
  629. // content).
  630. let message = error.message
  631. if (/^Delete component/.test(message)) {
  632. message = 'Delete component does not match deleted text'
  633. }
  634. ga(
  635. 'send',
  636. 'event',
  637. 'error',
  638. 'shareJsError',
  639. `${message} - ${this.ide.socket.socket.transport.name}`
  640. )
  641. }
  642. if (this.doc != null) {
  643. this.doc.clearInflightAndPendingOps()
  644. }
  645. this.trigger('error', error, meta, editorContent)
  646. // The clean up should run after the error is triggered because the error triggers a
  647. // disconnect. If we run the clean up first, we remove our event handlers and miss
  648. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  649. // This could intefere with the new connection of a new instance of this document.
  650. return this._cleanUp()
  651. }
  652. _applyOpsToRanges(ops, oldSnapshot, msg) {
  653. let old_id_seed
  654. if (ops == null) {
  655. ops = []
  656. }
  657. let track_changes_as = null
  658. const remote_op = msg != null
  659. if (__guard__(msg != null ? msg.meta : undefined, x => x.tc) != null) {
  660. old_id_seed = this.ranges.getIdSeed()
  661. this.ranges.setIdSeed(msg.meta.tc)
  662. }
  663. if (remote_op && (msg.meta != null ? msg.meta.tc : undefined)) {
  664. track_changes_as = msg.meta.user_id
  665. } else if (!remote_op && this.track_changes_as != null) {
  666. ;({ track_changes_as } = this)
  667. }
  668. this.ranges.track_changes = track_changes_as != null
  669. for (let op of Array.from(ops)) {
  670. this.ranges.applyOp(op, { user_id: track_changes_as })
  671. }
  672. if (old_id_seed != null) {
  673. this.ranges.setIdSeed(old_id_seed)
  674. }
  675. if (remote_op) {
  676. // With remote ops, Ace hasn't been updated when we receive this op,
  677. // so defer updating track changes until it has
  678. return setTimeout(() => this.emit('ranges:dirty'))
  679. } else {
  680. return this.emit('ranges:dirty')
  681. }
  682. }
  683. _catchUpRanges(changes, comments) {
  684. // We've just been given the current server's ranges, but need to apply any local ops we have.
  685. // Reset to the server state then apply our local ops again.
  686. if (changes == null) {
  687. changes = []
  688. }
  689. if (comments == null) {
  690. comments = []
  691. }
  692. this.emit('ranges:clear')
  693. this.ranges.changes = changes
  694. this.ranges.comments = comments
  695. this.ranges.track_changes = this.doc.track_changes
  696. for (var op of Array.from(this.doc.getInflightOp() || [])) {
  697. this.ranges.setIdSeed(this.doc.track_changes_id_seeds.inflight)
  698. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  699. }
  700. for (op of Array.from(this.doc.getPendingOp() || [])) {
  701. this.ranges.setIdSeed(this.doc.track_changes_id_seeds.pending)
  702. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  703. }
  704. return this.emit('ranges:redraw')
  705. }
  706. }
  707. Document.initClass()
  708. return Document
  709. })()
  710. function __guard__(value, transform) {
  711. return typeof value !== 'undefined' && value !== null
  712. ? transform(value)
  713. : undefined
  714. }