Document.js 22 KB

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