Document.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. import _ from 'lodash'
  2. /* eslint-disable
  3. camelcase,
  4. handle-callback-err,
  5. max-len,
  6. */
  7. // TODO: This file was created by bulk-decaffeinate.
  8. // Fix any style issues and re-enable lint.
  9. /*
  10. * decaffeinate suggestions:
  11. * DS001: Remove Babel/TypeScript constructor workaround
  12. * DS101: Remove unnecessary use of Array.from
  13. * DS102: Remove unnecessary code created because of implicit returns
  14. * DS103: Rewrite code to no longer use __guard__
  15. * DS205: Consider reworking code to avoid use of IIFEs
  16. * DS206: Consider reworking classes to avoid initClass
  17. * DS207: Consider shorter variations of null checks
  18. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  19. */
  20. import EventEmitter from '../../utils/EventEmitter'
  21. import ShareJsDoc from './ShareJsDoc'
  22. import RangesTracker from '../review-panel/RangesTracker'
  23. let Document
  24. export default (Document = (function() {
  25. Document = class Document extends EventEmitter {
  26. static initClass() {
  27. this.prototype.MAX_PENDING_OP_SIZE = 64
  28. }
  29. static getDocument(ide, doc_id) {
  30. if (!this.openDocs) {
  31. this.openDocs = {}
  32. }
  33. // Try to clean up existing docs before reopening them. If the doc has no
  34. // buffered ops then it will be deleted by _cleanup() and a new instance
  35. // of the document created below. This prevents us trying to follow the
  36. // joinDoc:existing code path on an existing doc that doesn't have any
  37. // local changes and getting an error if its version is too old.
  38. if (this.openDocs[doc_id]) {
  39. sl_console.log(
  40. `[getDocument] Cleaning up existing document instance for ${doc_id}`
  41. )
  42. this.openDocs[doc_id]._cleanUp()
  43. }
  44. if (this.openDocs[doc_id] == null) {
  45. sl_console.log(
  46. `[getDocument] Creating new document instance for ${doc_id}`
  47. )
  48. this.openDocs[doc_id] = new Document(ide, doc_id)
  49. } else {
  50. sl_console.log(
  51. `[getDocument] Returning existing document instance for ${doc_id}`
  52. )
  53. }
  54. return this.openDocs[doc_id]
  55. }
  56. static hasUnsavedChanges() {
  57. const object = this.openDocs || {}
  58. for (let doc_id in object) {
  59. const doc = object[doc_id]
  60. if (doc.hasBufferedOps()) {
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. static flushAll() {
  67. return (() => {
  68. const result = []
  69. for (let doc_id in this.openDocs) {
  70. const doc = this.openDocs[doc_id]
  71. result.push(doc.flush())
  72. }
  73. return result
  74. })()
  75. }
  76. constructor(ide, doc_id) {
  77. super()
  78. this.ide = ide
  79. this.doc_id = doc_id
  80. this.connected = this.ide.socket.socket.connected
  81. this.joined = false
  82. this.wantToBeJoined = false
  83. this._checkAceConsistency = _.bind(this._checkConsistency, this, this.ace)
  84. this._checkCMConsistency = _.bind(this._checkConsistency, this, this.cm)
  85. this._bindToEditorEvents()
  86. this._bindToSocketEvents()
  87. }
  88. attachToAce(ace) {
  89. this.ace = ace
  90. if (this.doc != null) {
  91. this.doc.attachToAce(this.ace)
  92. }
  93. const editorDoc = this.ace.getSession().getDocument()
  94. editorDoc.on('change', this._checkAceConsistency)
  95. return this.ide.$scope.$emit('document:opened', this.doc)
  96. }
  97. detachFromAce() {
  98. if (this.doc != null) {
  99. this.doc.detachFromAce()
  100. }
  101. const editorDoc =
  102. this.ace != null ? this.ace.getSession().getDocument() : undefined
  103. if (editorDoc != null) {
  104. editorDoc.off('change', this._checkAceConsistency)
  105. }
  106. return this.ide.$scope.$emit('document:closed', this.doc)
  107. }
  108. attachToCM(cm) {
  109. this.cm = cm
  110. if (this.doc != null) {
  111. this.doc.attachToCM(this.cm)
  112. }
  113. if (this.cm != null) {
  114. this.cm.on('change', this._checkCMConsistency)
  115. }
  116. return this.ide.$scope.$emit('document:opened', this.doc)
  117. }
  118. detachFromCM() {
  119. if (this.doc != null) {
  120. this.doc.detachFromCM()
  121. }
  122. if (this.cm != null) {
  123. this.cm.off('change', this._checkCMConsistency)
  124. }
  125. return this.ide.$scope.$emit('document:closed', this.doc)
  126. }
  127. submitOp(...args) {
  128. return this.doc != null
  129. ? this.doc.submitOp(...Array.from(args || []))
  130. : undefined
  131. }
  132. _checkConsistency(editor) {
  133. return () => {
  134. // We've been seeing a lot of errors when I think there shouldn't be
  135. // any, which may be related to this check happening before the change is
  136. // applied. If we use a timeout, hopefully we can reduce this.
  137. return setTimeout(() => {
  138. const editorValue = editor != null ? editor.getValue() : undefined
  139. const sharejsValue =
  140. this.doc != null ? this.doc.getSnapshot() : undefined
  141. if (editorValue !== sharejsValue) {
  142. return this._onError(
  143. new Error('Editor text does not match server text')
  144. )
  145. }
  146. }, 0)
  147. }
  148. }
  149. getSnapshot() {
  150. return this.doc != null ? this.doc.getSnapshot() : undefined
  151. }
  152. getType() {
  153. return this.doc != null ? this.doc.getType() : undefined
  154. }
  155. getInflightOp() {
  156. return this.doc != null ? this.doc.getInflightOp() : undefined
  157. }
  158. getPendingOp() {
  159. return this.doc != null ? this.doc.getPendingOp() : undefined
  160. }
  161. getRecentAck() {
  162. return this.doc != null ? this.doc.getRecentAck() : undefined
  163. }
  164. getOpSize(op) {
  165. return this.doc != null ? this.doc.getOpSize(op) : undefined
  166. }
  167. hasBufferedOps() {
  168. return this.doc != null ? this.doc.hasBufferedOps() : undefined
  169. }
  170. setTrackingChanges(track_changes) {
  171. return (this.doc.track_changes = track_changes)
  172. }
  173. getTrackingChanges() {
  174. return !!this.doc.track_changes
  175. }
  176. setTrackChangesIdSeeds(id_seeds) {
  177. return (this.doc.track_changes_id_seeds = id_seeds)
  178. }
  179. _bindToSocketEvents() {
  180. this._onUpdateAppliedHandler = update => this._onUpdateApplied(update)
  181. this.ide.socket.on('otUpdateApplied', this._onUpdateAppliedHandler)
  182. this._onErrorHandler = (error, update) => this._onError(error, update)
  183. this.ide.socket.on('otUpdateError', this._onErrorHandler)
  184. this._onDisconnectHandler = error => this._onDisconnect(error)
  185. return this.ide.socket.on('disconnect', this._onDisconnectHandler)
  186. }
  187. _bindToEditorEvents() {
  188. const onReconnectHandler = update => {
  189. return this._onReconnect(update)
  190. }
  191. return (this._unsubscribeReconnectHandler = this.ide.$scope.$on(
  192. 'project:joined',
  193. onReconnectHandler
  194. ))
  195. }
  196. _unBindFromEditorEvents() {
  197. return this._unsubscribeReconnectHandler()
  198. }
  199. _unBindFromSocketEvents() {
  200. this.ide.socket.removeListener(
  201. 'otUpdateApplied',
  202. this._onUpdateAppliedHandler
  203. )
  204. this.ide.socket.removeListener('otUpdateError', this._onErrorHandler)
  205. return this.ide.socket.removeListener(
  206. 'disconnect',
  207. this._onDisconnectHandler
  208. )
  209. }
  210. leaveAndCleanUp() {
  211. return this.leave(error => {
  212. return this._cleanUp()
  213. })
  214. }
  215. join(callback) {
  216. if (callback == null) {
  217. callback = function(error) {}
  218. }
  219. this.wantToBeJoined = true
  220. this._cancelLeave()
  221. if (this.connected) {
  222. return this._joinDoc(callback)
  223. } else {
  224. if (!this._joinCallbacks) {
  225. this._joinCallbacks = []
  226. }
  227. return this._joinCallbacks.push(callback)
  228. }
  229. }
  230. leave(callback) {
  231. if (callback == null) {
  232. callback = function(error) {}
  233. }
  234. this.flush() // force an immediate flush when leaving document
  235. this.wantToBeJoined = false
  236. this._cancelJoin()
  237. if (this.doc != null && this.doc.hasBufferedOps()) {
  238. sl_console.log(
  239. '[leave] Doc has buffered ops, pushing callback for later'
  240. )
  241. if (!this._leaveCallbacks) {
  242. this._leaveCallbacks = []
  243. }
  244. return this._leaveCallbacks.push(callback)
  245. } else if (!this.connected) {
  246. sl_console.log('[leave] Not connected, returning now')
  247. return callback()
  248. } else {
  249. sl_console.log('[leave] Leaving now')
  250. return this._leaveDoc(callback)
  251. }
  252. }
  253. flush() {
  254. return this.doc != null ? this.doc.flushPendingOps() : undefined
  255. }
  256. chaosMonkey(line, char) {
  257. if (line == null) {
  258. line = 0
  259. }
  260. if (char == null) {
  261. char = 'a'
  262. }
  263. const orig = char
  264. let copy = null
  265. let pos = 0
  266. var timer = () => {
  267. if (copy == null || !copy.length) {
  268. copy = orig.slice() + ' ' + new Date() + '\n'
  269. line += Math.random() > 0.1 ? 1 : -2
  270. if (line < 0) {
  271. line = 0
  272. }
  273. pos = 0
  274. }
  275. char = copy[0]
  276. copy = copy.slice(1)
  277. this.ace.session.insert({ row: line, column: pos }, char)
  278. pos += 1
  279. return (this._cm = setTimeout(
  280. timer,
  281. 100 + (Math.random() < 0.1 ? 1000 : 0)
  282. ))
  283. }
  284. return (this._cm = timer())
  285. }
  286. clearChaosMonkey() {
  287. return clearTimeout(this._cm) // pending ops bigger than this are always considered unsaved
  288. }
  289. pollSavedStatus() {
  290. // returns false if doc has ops waiting to be acknowledged or
  291. // sent that haven't changed since the last time we checked.
  292. // Otherwise returns true.
  293. let saved
  294. const inflightOp = this.getInflightOp()
  295. const pendingOp = this.getPendingOp()
  296. const recentAck = this.getRecentAck()
  297. const pendingOpSize = pendingOp != null && this.getOpSize(pendingOp)
  298. if (inflightOp == null && pendingOp == null) {
  299. // there's nothing going on, this is ok.
  300. saved = true
  301. sl_console.logOnce('[pollSavedStatus] no inflight or pending ops')
  302. } else if (inflightOp != null && inflightOp === this.oldInflightOp) {
  303. // The same inflight op has been sitting unacked since we
  304. // last checked, this is bad.
  305. saved = false
  306. sl_console.log('[pollSavedStatus] inflight op is same as before')
  307. } else if (
  308. pendingOp != null &&
  309. recentAck &&
  310. pendingOpSize < this.MAX_PENDING_OP_SIZE
  311. ) {
  312. // There is an op waiting to go to server but it is small and
  313. // within the flushDelay, this is ok for now.
  314. saved = true
  315. sl_console.log(
  316. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  317. pendingOp,
  318. pendingOpSize
  319. )
  320. } else {
  321. // In any other situation, assume the document is unsaved.
  322. saved = false
  323. sl_console.log(
  324. `[pollSavedStatus] assuming not saved (inflightOp?: ${inflightOp !=
  325. null}, pendingOp?: ${pendingOp != null})`
  326. )
  327. }
  328. this.oldInflightOp = inflightOp
  329. return saved
  330. }
  331. _cancelLeave() {
  332. if (this._leaveCallbacks != null) {
  333. return delete this._leaveCallbacks
  334. }
  335. }
  336. _cancelJoin() {
  337. if (this._joinCallbacks != null) {
  338. return delete this._joinCallbacks
  339. }
  340. }
  341. _onUpdateApplied(update) {
  342. this.ide.pushEvent('received-update', {
  343. doc_id: this.doc_id,
  344. remote_doc_id: update != null ? update.doc : undefined,
  345. wantToBeJoined: this.wantToBeJoined,
  346. update,
  347. hasDoc: this.doc != null
  348. })
  349. if (
  350. window.disconnectOnAck != null &&
  351. Math.random() < window.disconnectOnAck
  352. ) {
  353. sl_console.log('Disconnecting on ack', update)
  354. window._ide.socket.socket.disconnect()
  355. // Pretend we never received the ack
  356. return
  357. }
  358. if (window.dropAcks != null && Math.random() < window.dropAcks) {
  359. if (update.op == null) {
  360. // Only drop our own acks, not collaborator updates
  361. sl_console.log('Simulating a lost ack', update)
  362. return
  363. }
  364. }
  365. if (
  366. (update != null ? update.doc : undefined) === this.doc_id &&
  367. this.doc != null
  368. ) {
  369. this.ide.pushEvent('received-update:processing', {
  370. update
  371. })
  372. // FIXME: change this back to processUpdateFromServer when redis fixed
  373. this.doc.processUpdateFromServerInOrder(update)
  374. if (!this.wantToBeJoined) {
  375. return this.leave()
  376. }
  377. }
  378. }
  379. _onDisconnect() {
  380. sl_console.log('[onDisconnect] disconnecting')
  381. this.connected = false
  382. this.joined = false
  383. return this.doc != null
  384. ? this.doc.updateConnectionState('disconnected')
  385. : undefined
  386. }
  387. _onReconnect() {
  388. sl_console.log('[onReconnect] reconnected (joined project)')
  389. this.ide.pushEvent('reconnected:afterJoinProject')
  390. this.connected = true
  391. if (
  392. this.wantToBeJoined ||
  393. (this.doc != null ? this.doc.hasBufferedOps() : undefined)
  394. ) {
  395. sl_console.log(
  396. `[onReconnect] Rejoining (wantToBeJoined: ${
  397. this.wantToBeJoined
  398. } OR hasBufferedOps: ${
  399. this.doc != null ? this.doc.hasBufferedOps() : undefined
  400. })`
  401. )
  402. return this._joinDoc(error => {
  403. if (error != null) {
  404. return this._onError(error)
  405. }
  406. this.doc.updateConnectionState('ok')
  407. this.doc.flushPendingOps()
  408. return this._callJoinCallbacks()
  409. })
  410. }
  411. }
  412. _callJoinCallbacks() {
  413. for (let callback of Array.from(this._joinCallbacks || [])) {
  414. callback()
  415. }
  416. return delete this._joinCallbacks
  417. }
  418. _joinDoc(callback) {
  419. if (callback == null) {
  420. callback = function(error) {}
  421. }
  422. if (this.doc != null) {
  423. this.ide.pushEvent('joinDoc:existing', {
  424. doc_id: this.doc_id,
  425. version: this.doc.getVersion()
  426. })
  427. return this.ide.socket.emit(
  428. 'joinDoc',
  429. this.doc_id,
  430. this.doc.getVersion(),
  431. { encodeRanges: true },
  432. (error, docLines, version, updates, ranges) => {
  433. if (error != null) {
  434. return callback(error)
  435. }
  436. this.joined = true
  437. this.doc.catchUp(updates)
  438. this._decodeRanges(ranges)
  439. this._catchUpRanges(
  440. ranges != null ? ranges.changes : undefined,
  441. ranges != null ? ranges.comments : undefined
  442. )
  443. return callback()
  444. }
  445. )
  446. } else {
  447. this.ide.pushEvent('joinDoc:new', {
  448. doc_id: this.doc_id
  449. })
  450. return this.ide.socket.emit(
  451. 'joinDoc',
  452. this.doc_id,
  453. { encodeRanges: true },
  454. (error, docLines, version, updates, ranges) => {
  455. if (error != null) {
  456. return callback(error)
  457. }
  458. this.joined = true
  459. this.ide.pushEvent('joinDoc:inited', {
  460. doc_id: this.doc_id,
  461. version
  462. })
  463. this.doc = new ShareJsDoc(
  464. this.doc_id,
  465. docLines,
  466. version,
  467. this.ide.socket
  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) {
  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)
  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. }