Document.js 24 KB

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