Document.js 23 KB

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