Document.js 24 KB

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