Document.js 24 KB

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