Document.js 24 KB

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