Document.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. )
  468. this._decodeRanges(ranges)
  469. this.ranges = new RangesTracker(
  470. ranges != null ? ranges.changes : undefined,
  471. ranges != null ? ranges.comments : undefined
  472. )
  473. this._bindToShareJsDocEvents()
  474. return callback()
  475. }
  476. )
  477. }
  478. }
  479. _decodeRanges(ranges) {
  480. const decodeFromWebsockets = text => decodeURIComponent(escape(text))
  481. try {
  482. for (let change of Array.from(ranges.changes || [])) {
  483. if (change.op.i != null) {
  484. change.op.i = decodeFromWebsockets(change.op.i)
  485. }
  486. if (change.op.d != null) {
  487. change.op.d = decodeFromWebsockets(change.op.d)
  488. }
  489. }
  490. return (() => {
  491. const result = []
  492. for (let comment of Array.from(ranges.comments || [])) {
  493. if (comment.op.c != null) {
  494. result.push((comment.op.c = decodeFromWebsockets(comment.op.c)))
  495. } else {
  496. result.push(undefined)
  497. }
  498. }
  499. return result
  500. })()
  501. } catch (err) {
  502. return console.log(err)
  503. }
  504. }
  505. _leaveDoc(callback) {
  506. if (callback == null) {
  507. callback = function(error) {}
  508. }
  509. this.ide.pushEvent('leaveDoc', {
  510. doc_id: this.doc_id
  511. })
  512. sl_console.log('[_leaveDoc] Sending leaveDoc request')
  513. return this.ide.socket.emit('leaveDoc', this.doc_id, error => {
  514. if (error != null) {
  515. return callback(error)
  516. }
  517. this.joined = false
  518. for (callback of Array.from(this._leaveCallbacks || [])) {
  519. sl_console.log('[_leaveDoc] Calling buffered callback', callback)
  520. callback(error)
  521. }
  522. delete this._leaveCallbacks
  523. return callback(error)
  524. })
  525. }
  526. _cleanUp() {
  527. // if we arrive here from _onError the pending and inflight ops will have been cleared
  528. if (this.hasBufferedOps()) {
  529. sl_console.log(
  530. `[_cleanUp] Document (${
  531. this.doc_id
  532. }) has buffered ops, refusing to remove from openDocs`
  533. )
  534. return // return immediately, do not unbind from events
  535. } else if (Document.openDocs[this.doc_id] === this) {
  536. sl_console.log(
  537. `[_cleanUp] Removing self (${this.doc_id}) from in openDocs`
  538. )
  539. delete Document.openDocs[this.doc_id]
  540. } else {
  541. // It's possible that this instance has error, and the doc has been reloaded.
  542. // This creates a new instance in Document.openDoc with the same id. We shouldn't
  543. // clear it because it's not this instance.
  544. sl_console.log(
  545. `[_cleanUp] New instance of (${this.doc_id}) created. Not removing`
  546. )
  547. }
  548. this._unBindFromEditorEvents()
  549. return this._unBindFromSocketEvents()
  550. }
  551. _bindToShareJsDocEvents() {
  552. this.doc.on('error', (error, meta) => this._onError(error, meta))
  553. this.doc.on('externalUpdate', update => {
  554. this.ide.pushEvent('externalUpdate', { doc_id: this.doc_id })
  555. return this.trigger('externalUpdate', update)
  556. })
  557. this.doc.on('remoteop', (...args) => {
  558. this.ide.pushEvent('remoteop', { doc_id: this.doc_id })
  559. return this.trigger('remoteop', ...Array.from(args))
  560. })
  561. this.doc.on('op:sent', op => {
  562. this.ide.pushEvent('op:sent', {
  563. doc_id: this.doc_id,
  564. op
  565. })
  566. return this.trigger('op:sent')
  567. })
  568. this.doc.on('op:acknowledged', op => {
  569. this.ide.pushEvent('op:acknowledged', {
  570. doc_id: this.doc_id,
  571. op
  572. })
  573. this.ide.$scope.$emit('ide:opAcknowledged', {
  574. doc_id: this.doc_id,
  575. op
  576. })
  577. return this.trigger('op:acknowledged')
  578. })
  579. this.doc.on('op:timeout', op => {
  580. this.ide.pushEvent('op:timeout', {
  581. doc_id: this.doc_id,
  582. op
  583. })
  584. this.trigger('op:timeout')
  585. return this._onError(new Error('op timed out'), { op })
  586. })
  587. this.doc.on('flush', (inflightOp, pendingOp, version) => {
  588. return this.ide.pushEvent('flush', {
  589. doc_id: this.doc_id,
  590. inflightOp,
  591. pendingOp,
  592. v: version
  593. })
  594. })
  595. this.doc.on('change', (ops, oldSnapshot, msg) => {
  596. this._applyOpsToRanges(ops, oldSnapshot, msg)
  597. return this.ide.$scope.$emit('doc:changed', { doc_id: this.doc_id })
  598. })
  599. this.doc.on('flipped_pending_to_inflight', () => {
  600. return this.trigger('flipped_pending_to_inflight')
  601. })
  602. return this.doc.on('saved', () => {
  603. return this.ide.$scope.$emit('doc:saved', { doc_id: this.doc_id })
  604. })
  605. }
  606. _onError(error, meta, editorContent) {
  607. if (meta == null) {
  608. meta = {}
  609. }
  610. meta.doc_id = this.doc_id
  611. sl_console.log('ShareJS error', error, meta)
  612. if (error.message === 'no project_id found on client') {
  613. sl_console.log('ignoring error, will wait to join project')
  614. return
  615. }
  616. if (typeof ga === 'function') {
  617. // sanitise the error message before sending (the "delete component"
  618. // error in public/js/libs/sharejs.js includes the some document
  619. // content).
  620. let message = error.message
  621. if (/^Delete component/.test(message)) {
  622. message = 'Delete component does not match deleted text'
  623. }
  624. ga(
  625. 'send',
  626. 'event',
  627. 'error',
  628. 'shareJsError',
  629. `${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, editorContent)
  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. function __guard__(value, transform) {
  701. return typeof value !== 'undefined' && value !== null
  702. ? transform(value)
  703. : undefined
  704. }