Document.js 23 KB

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