Document.js 24 KB

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