Document.js 24 KB

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