Document.js 25 KB

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