document-container.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /* eslint-disable camelcase */
  2. // Migrated from services/web/frontend/js/ide/editor/Document.js
  3. import RangesTracker from '@overleaf/ranges-tracker'
  4. import { ShareJsDoc } from './share-js-doc'
  5. import { debugConsole } from '@/utils/debugging'
  6. import { Socket } from '@/features/ide-react/connection/types/socket'
  7. import { IdeEventEmitter } from '@/features/ide-react/create-ide-event-emitter'
  8. import { EditorFacade } from '@/features/source-editor/extensions/realtime'
  9. import { EventLog } from '@/features/ide-react/editor/event-log'
  10. import EditorWatchdogManager from '@/features/ide-react/connection/editor-watchdog-manager'
  11. import EventEmitter from '@/utils/EventEmitter'
  12. import {
  13. AnyOperation,
  14. Change,
  15. CommentOperation,
  16. EditOperation,
  17. } from '../../../../../types/change'
  18. import {
  19. isCommentOperation,
  20. isDeleteOperation,
  21. isInsertOperation,
  22. } from '@/utils/operations'
  23. import { decodeUtf8 } from '@/utils/decode-utf8'
  24. import {
  25. ShareJsOperation,
  26. TrackChangesIdSeeds,
  27. Version,
  28. } from '@/features/ide-react/editor/types/document'
  29. import { ThreadId } from '../../../../../types/review-panel/review-panel'
  30. const MAX_PENDING_OP_SIZE = 64
  31. type JoinCallback = (error?: Error) => void
  32. type LeaveCallback = JoinCallback
  33. type Update =
  34. | {
  35. v: number
  36. doc: string
  37. }
  38. | {
  39. v: number
  40. doc: string
  41. op: AnyOperation[]
  42. meta: {
  43. type?: string
  44. source: string
  45. user_id: string
  46. ts: number
  47. }
  48. hash?: string
  49. lastV?: number
  50. }
  51. type Message = {
  52. meta: {
  53. tc: string
  54. user_id: string
  55. }
  56. }
  57. type ErrorMetadata = Record<string, any>
  58. function getOpSize(op: AnyOperation) {
  59. if (isInsertOperation(op)) {
  60. return op.i.length
  61. }
  62. if (isDeleteOperation(op)) {
  63. return op.d.length
  64. }
  65. return 0
  66. }
  67. function getShareJsOpSize(shareJsOp: ShareJsOperation) {
  68. return shareJsOp.reduce((total, op) => total + getOpSize(op), 0)
  69. }
  70. // TODO: define these in RangesTracker
  71. type _RangesTracker = Omit<RangesTracker, 'changes' | 'comments'> & {
  72. changes: Change<EditOperation>[]
  73. comments: Change<CommentOperation>[]
  74. track_changes?: boolean
  75. }
  76. export type RangesTrackerWithResolvedThreadIds = _RangesTracker & {
  77. resolvedThreadIds: Record<ThreadId, boolean>
  78. }
  79. export class DocumentContainer extends EventEmitter {
  80. private connected: boolean
  81. private wantToBeJoined = false
  82. private chaosMonkeyTimer: number | null = null
  83. public track_changes_as: string | null = null
  84. private joinCallbacks: JoinCallback[] = []
  85. private leaveCallbacks: LeaveCallback[] = []
  86. doc?: ShareJsDoc
  87. cm6?: EditorFacade
  88. oldInflightOp?: ShareJsOperation
  89. ranges?: _RangesTracker | RangesTrackerWithResolvedThreadIds
  90. joined = false
  91. // This is set and read in useCodeMirrorScope
  92. docName = ''
  93. constructor(
  94. readonly doc_id: string,
  95. readonly socket: Socket,
  96. private readonly globalEditorWatchdogManager: EditorWatchdogManager,
  97. private readonly ideEventEmitter: IdeEventEmitter,
  98. private readonly eventLog: EventLog,
  99. private readonly detachDoc: (docId: string, doc: DocumentContainer) => void
  100. ) {
  101. super()
  102. this.connected = this.socket.socket.connected
  103. this.bindToEditorEvents()
  104. this.bindToSocketEvents()
  105. }
  106. attachToCM6(cm6: EditorFacade) {
  107. this.cm6 = cm6
  108. if (this.doc) {
  109. this.doc.attachToCM6(this.cm6)
  110. }
  111. if (this.cm6) {
  112. this.cm6.on('change', this.checkConsistency)
  113. }
  114. }
  115. detachFromCM6() {
  116. if (this.doc) {
  117. this.doc.detachFromCM6()
  118. }
  119. if (this.cm6) {
  120. this.cm6.off('change', this.checkConsistency)
  121. }
  122. delete this.cm6
  123. this.clearChaosMonkey()
  124. if (this.doc) {
  125. this.ideEventEmitter.emit('document:closed', this.doc)
  126. }
  127. }
  128. submitOp(...ops: AnyOperation[]) {
  129. this.doc?.submitOp(ops)
  130. }
  131. private checkConsistency = (editor: EditorFacade) => {
  132. // We've been seeing a lot of errors when I think there shouldn't be
  133. // any, which may be related to this check happening before the change is
  134. // applied. If we use a timeout, hopefully we can reduce this.
  135. window.setTimeout(() => {
  136. const editorValue = editor?.getValue()
  137. const sharejsValue = this.doc?.getSnapshot()
  138. if (editorValue !== sharejsValue) {
  139. return this.onError(
  140. new Error('Editor text does not match server text'),
  141. {},
  142. editorValue
  143. )
  144. }
  145. }, 0)
  146. }
  147. getSnapshot() {
  148. return this.doc?.getSnapshot()
  149. }
  150. getType() {
  151. return this.doc?.getType()
  152. }
  153. getInflightOp(): ShareJsOperation | undefined {
  154. return this.doc?.getInflightOp()
  155. }
  156. getPendingOp(): ShareJsOperation | undefined {
  157. return this.doc?.getPendingOp()
  158. }
  159. getRecentAck() {
  160. return this.doc?.getRecentAck()
  161. }
  162. hasBufferedOps() {
  163. return this.doc?.hasBufferedOps()
  164. }
  165. setTrackingChanges(track_changes: boolean) {
  166. if (this.doc) {
  167. this.doc.track_changes = track_changes
  168. }
  169. }
  170. getTrackingChanges() {
  171. return !!this.doc?.track_changes
  172. }
  173. setTrackChangesIdSeeds(id_seeds: TrackChangesIdSeeds) {
  174. if (this.doc) {
  175. this.doc.track_changes_id_seeds = id_seeds
  176. }
  177. }
  178. private onUpdateAppliedHandler = (update: any) => this.onUpdateApplied(update)
  179. private onErrorHandler = (error: Error, message: ErrorMetadata) => {
  180. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  181. // sure that message.doc_id exists.
  182. if (message.doc_id !== this.doc_id) {
  183. // This error is for another doc. Do not action it. We could open
  184. // a modal that has the wrong context on it.
  185. return
  186. }
  187. this.onError(error, message)
  188. }
  189. private onDisconnectHandler = () => this.onDisconnect()
  190. private bindToSocketEvents() {
  191. this.socket.on('otUpdateApplied', this.onUpdateAppliedHandler)
  192. this.socket.on('otUpdateError', this.onErrorHandler)
  193. return this.socket.on('disconnect', this.onDisconnectHandler)
  194. }
  195. private unBindFromSocketEvents() {
  196. this.socket.removeListener('otUpdateApplied', this.onUpdateAppliedHandler)
  197. this.socket.removeListener('otUpdateError', this.onErrorHandler)
  198. return this.socket.removeListener('disconnect', this.onDisconnectHandler)
  199. }
  200. private bindToEditorEvents() {
  201. this.ideEventEmitter.on('project:joined', this.onReconnect)
  202. }
  203. private unBindFromEditorEvents() {
  204. this.ideEventEmitter.off('project:joined', this.onReconnect)
  205. }
  206. leaveAndCleanUp(cb?: (error?: Error) => void) {
  207. return this.leave((error?: Error) => {
  208. this.cleanUp()
  209. if (cb) cb(error)
  210. })
  211. }
  212. leaveAndCleanUpPromise() {
  213. return new Promise<void>((resolve, reject) => {
  214. this.leaveAndCleanUp((error?: Error) => {
  215. if (error) {
  216. reject(error)
  217. } else {
  218. resolve()
  219. }
  220. })
  221. })
  222. }
  223. join(callback?: JoinCallback) {
  224. this.wantToBeJoined = true
  225. this.cancelLeave()
  226. if (this.connected) {
  227. this.joinDoc(callback)
  228. } else if (callback) {
  229. this.joinCallbacks.push(callback)
  230. }
  231. }
  232. leave(callback?: LeaveCallback) {
  233. this.flush() // force an immediate flush when leaving document
  234. this.wantToBeJoined = false
  235. this.cancelJoin()
  236. if (this.doc?.hasBufferedOps()) {
  237. debugConsole.log(
  238. '[leave] Doc has buffered ops, pushing callback for later'
  239. )
  240. if (callback) {
  241. this.leaveCallbacks.push(callback)
  242. }
  243. } else if (!this.connected) {
  244. debugConsole.log('[leave] Not connected, returning now')
  245. callback?.()
  246. } else {
  247. debugConsole.log('[leave] Leaving now')
  248. this.leaveDoc(callback)
  249. }
  250. }
  251. flush() {
  252. return this.doc?.flushPendingOps()
  253. }
  254. chaosMonkey(line = 0, char = 'a') {
  255. const orig = char
  256. let copy: string | null = null
  257. let pos = 0
  258. const timer = () => {
  259. if (copy == null || !copy.length) {
  260. copy = orig.slice() + ' ' + new Date() + '\n'
  261. line += Math.random() > 0.1 ? 1 : -2
  262. if (line < 0) {
  263. line = 0
  264. }
  265. pos = 0
  266. }
  267. char = copy[0]
  268. copy = copy.slice(1)
  269. if (this.cm6) {
  270. this.cm6.view.dispatch({
  271. changes: {
  272. from: Math.min(pos, this.cm6.view.state.doc.length),
  273. insert: char,
  274. },
  275. })
  276. }
  277. pos += 1
  278. this.chaosMonkeyTimer = window.setTimeout(
  279. timer,
  280. 100 + (Math.random() < 0.1 ? 1000 : 0)
  281. )
  282. }
  283. timer()
  284. }
  285. clearChaosMonkey() {
  286. const timer = this.chaosMonkeyTimer
  287. if (timer) {
  288. this.chaosMonkeyTimer = null
  289. window.clearTimeout(timer)
  290. }
  291. }
  292. pollSavedStatus() {
  293. // returns false if doc has ops waiting to be acknowledged or
  294. // sent that haven't changed since the last time we checked.
  295. // Otherwise returns true.
  296. let saved
  297. const inflightOp = this.getInflightOp()
  298. const pendingOp = this.getPendingOp()
  299. const recentAck = this.getRecentAck()
  300. const pendingOpSize = pendingOp ? getShareJsOpSize(pendingOp) : 0
  301. if (inflightOp == null && pendingOp == null) {
  302. // There's nothing going on, this is OK.
  303. saved = true
  304. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  305. } else if (inflightOp && inflightOp === this.oldInflightOp) {
  306. // The same inflight op has been sitting unacked since we
  307. // last checked, this is bad.
  308. saved = false
  309. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  310. } else if (
  311. pendingOp != null &&
  312. recentAck &&
  313. pendingOpSize < MAX_PENDING_OP_SIZE
  314. ) {
  315. // There is an op waiting to go to server but it is small and
  316. // within the flushDelay, this is OK for now.
  317. saved = true
  318. debugConsole.log(
  319. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  320. pendingOp,
  321. pendingOpSize
  322. )
  323. } else {
  324. // In any other situation, assume the document is unsaved.
  325. saved = false
  326. debugConsole.log(
  327. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  328. inflightOp != null
  329. }, pendingOp?: ${pendingOp != null})`
  330. )
  331. }
  332. this.oldInflightOp = inflightOp
  333. return saved
  334. }
  335. private cancelLeave() {
  336. this.leaveCallbacks = []
  337. }
  338. private cancelJoin() {
  339. this.joinCallbacks = []
  340. }
  341. private onUpdateApplied(update: Update) {
  342. this.eventLog.pushEvent('received-update', {
  343. doc_id: this.doc_id,
  344. remote_doc_id: update?.doc,
  345. wantToBeJoined: this.wantToBeJoined,
  346. update,
  347. hasDoc: !!this.doc,
  348. })
  349. if (update?.doc === this.doc_id && this.doc != null) {
  350. this.eventLog.pushEvent('received-update:processing', {
  351. update,
  352. })
  353. // FIXME: change this back to processUpdateFromServer when redis fixed
  354. this.doc.processUpdateFromServerInOrder(update)
  355. if (!this.wantToBeJoined) {
  356. return this.leave()
  357. }
  358. }
  359. }
  360. private onDisconnect() {
  361. debugConsole.log('[onDisconnect] disconnecting')
  362. this.connected = false
  363. this.joined = false
  364. return this.doc != null
  365. ? this.doc.updateConnectionState('disconnected')
  366. : undefined
  367. }
  368. private onReconnect = () => {
  369. debugConsole.log('[onReconnect] reconnected (joined project)')
  370. this.eventLog.pushEvent('reconnected:afterJoinProject')
  371. this.connected = true
  372. if (this.wantToBeJoined || this.doc?.hasBufferedOps()) {
  373. debugConsole.log(
  374. `[onReconnect] Rejoining (wantToBeJoined: ${
  375. this.wantToBeJoined
  376. } OR hasBufferedOps: ${this.doc?.hasBufferedOps()})`
  377. )
  378. this.joinDoc((error?: Error) => {
  379. if (error) {
  380. this.onError(error)
  381. return
  382. }
  383. this.doc?.updateConnectionState('ok')
  384. this.doc?.flushPendingOps()
  385. this.callJoinCallbacks()
  386. })
  387. }
  388. }
  389. private callJoinCallbacks() {
  390. for (const callback of this.joinCallbacks) {
  391. callback()
  392. }
  393. this.joinCallbacks = []
  394. }
  395. private joinDoc(callback?: JoinCallback) {
  396. if (this.doc) {
  397. this.eventLog.pushEvent('joinDoc:existing', {
  398. doc_id: this.doc_id,
  399. version: this.doc.getVersion(),
  400. })
  401. return this.socket.emit(
  402. 'joinDoc',
  403. this.doc_id,
  404. this.doc.getVersion(),
  405. { encodeRanges: true },
  406. (error, docLines, version, updates, ranges) => {
  407. if (error) {
  408. callback?.(error)
  409. return
  410. }
  411. this.joined = true
  412. this.doc?.catchUp(updates)
  413. this.decodeRanges(ranges)
  414. this.catchUpRanges(ranges?.changes, ranges?.comments)
  415. callback?.()
  416. }
  417. )
  418. } else {
  419. this.eventLog.pushEvent('joinDoc:new', {
  420. doc_id: this.doc_id,
  421. })
  422. this.socket.emit(
  423. 'joinDoc',
  424. this.doc_id,
  425. { encodeRanges: true },
  426. (error, docLines, version, updates, ranges) => {
  427. if (error) {
  428. callback?.(error)
  429. return
  430. }
  431. this.joined = true
  432. this.eventLog.pushEvent('joinDoc:inited', {
  433. doc_id: this.doc_id,
  434. version,
  435. })
  436. this.doc = new ShareJsDoc(
  437. this.doc_id,
  438. docLines,
  439. version,
  440. this.socket,
  441. this.globalEditorWatchdogManager,
  442. this.ideEventEmitter,
  443. this.eventLog
  444. )
  445. this.decodeRanges(ranges)
  446. this.ranges = new RangesTracker(ranges?.changes, ranges?.comments)
  447. this.bindToShareJsDocEvents()
  448. callback?.()
  449. }
  450. )
  451. }
  452. }
  453. private decodeRanges(ranges: RangesTracker) {
  454. try {
  455. if (ranges.changes) {
  456. for (const change of ranges.changes) {
  457. if (isInsertOperation(change.op)) {
  458. change.op.i = decodeUtf8(change.op.i)
  459. }
  460. if (isDeleteOperation(change.op)) {
  461. change.op.d = decodeUtf8(change.op.d)
  462. }
  463. }
  464. }
  465. return (() => {
  466. if (!ranges.comments) {
  467. return []
  468. }
  469. return ranges.comments.map((comment: Change<CommentOperation>) =>
  470. comment.op.c != null
  471. ? (comment.op.c = decodeUtf8(comment.op.c))
  472. : undefined
  473. )
  474. })()
  475. } catch (err) {
  476. debugConsole.error(err)
  477. }
  478. }
  479. private leaveDoc(callback?: LeaveCallback) {
  480. this.eventLog.pushEvent('leaveDoc', {
  481. doc_id: this.doc_id,
  482. })
  483. debugConsole.log('[leaveDoc] Sending leaveDoc request')
  484. this.socket.emit('leaveDoc', this.doc_id, error => {
  485. if (error) {
  486. callback?.(error)
  487. return
  488. }
  489. this.joined = false
  490. for (const leaveCallback of this.leaveCallbacks) {
  491. debugConsole.log('[_leaveDoc] Calling buffered callback', leaveCallback)
  492. leaveCallback(error)
  493. }
  494. this.leaveCallbacks = []
  495. callback?.()
  496. })
  497. }
  498. cleanUp() {
  499. // if we arrive here from _onError the pending and inflight ops will have been cleared
  500. if (this.hasBufferedOps()) {
  501. debugConsole.log(
  502. `[cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  503. )
  504. return // return immediately, do not unbind from events
  505. }
  506. this.detachDoc(this.doc_id, this)
  507. this.unBindFromEditorEvents()
  508. this.unBindFromSocketEvents()
  509. }
  510. private bindToShareJsDocEvents() {
  511. if (!this.doc) {
  512. return
  513. }
  514. this.doc.on('error', (error: Error, meta: ErrorMetadata) =>
  515. this.onError(error, meta)
  516. )
  517. this.doc.on('externalUpdate', (update: Update) => {
  518. this.eventLog.pushEvent('externalUpdate', { doc_id: this.doc_id })
  519. return this.trigger('externalUpdate', update)
  520. })
  521. this.doc.on('remoteop', (...ops: AnyOperation[]) => {
  522. this.eventLog.pushEvent('remoteop', { doc_id: this.doc_id })
  523. return this.trigger('remoteop', ...ops)
  524. })
  525. this.doc.on('op:sent', (op: AnyOperation) => {
  526. this.eventLog.pushEvent('op:sent', {
  527. doc_id: this.doc_id,
  528. op,
  529. })
  530. return this.trigger('op:sent')
  531. })
  532. this.doc.on('op:acknowledged', (op: AnyOperation) => {
  533. this.eventLog.pushEvent('op:acknowledged', {
  534. doc_id: this.doc_id,
  535. op,
  536. })
  537. this.ideEventEmitter.emit('ide:opAcknowledged', {
  538. doc_id: this.doc_id,
  539. op,
  540. })
  541. return this.trigger('op:acknowledged')
  542. })
  543. this.doc.on('op:timeout', (op: AnyOperation) => {
  544. this.eventLog.pushEvent('op:timeout', {
  545. doc_id: this.doc_id,
  546. op,
  547. })
  548. this.trigger('op:timeout')
  549. return this.onError(new Error('op timed out'))
  550. })
  551. this.doc.on(
  552. 'flush',
  553. (inflightOp: AnyOperation, pendingOp: AnyOperation, version: Version) => {
  554. return this.eventLog.pushEvent('flush', {
  555. doc_id: this.doc_id,
  556. inflightOp,
  557. pendingOp,
  558. v: version,
  559. })
  560. }
  561. )
  562. let docChangedTimeout: number | null = null
  563. this.doc.on(
  564. 'change',
  565. (ops: AnyOperation[], oldSnapshot: any, msg: Message) => {
  566. this.applyOpsToRanges(ops, msg)
  567. if (docChangedTimeout) {
  568. window.clearTimeout(docChangedTimeout)
  569. }
  570. docChangedTimeout = window.setTimeout(() => {
  571. window.dispatchEvent(
  572. new CustomEvent('doc:changed', { detail: { id: this.doc_id } })
  573. )
  574. this.ideEventEmitter.emit('doc:changed', { doc_id: this.doc_id })
  575. }, 50)
  576. }
  577. )
  578. this.doc.on('flipped_pending_to_inflight', () => {
  579. return this.trigger('flipped_pending_to_inflight')
  580. })
  581. let docSavedTimeout: number | null
  582. this.doc.on('saved', () => {
  583. if (docSavedTimeout) {
  584. window.clearTimeout(docSavedTimeout)
  585. }
  586. docSavedTimeout = window.setTimeout(() => {
  587. window.dispatchEvent(
  588. new CustomEvent('doc:saved', { detail: { id: this.doc_id } })
  589. )
  590. this.ideEventEmitter.emit('doc:saved', { doc_id: this.doc_id })
  591. }, 50)
  592. })
  593. }
  594. private onError(
  595. error: Error,
  596. meta: ErrorMetadata = {},
  597. editorContent?: string
  598. ) {
  599. meta.doc_id = this.doc_id
  600. debugConsole.log('ShareJS error', error, meta)
  601. if (error.message === 'no project_id found on client') {
  602. debugConsole.log('ignoring error, will wait to join project')
  603. return
  604. }
  605. if (this.doc) {
  606. this.doc.clearInflightAndPendingOps()
  607. }
  608. this.trigger('error', error, meta, editorContent)
  609. // The clean-up should run after the error is triggered because the error triggers a
  610. // disconnect. If we run the clean-up first, we remove our event handlers and miss
  611. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  612. // This could interfere with the new connection of a new instance of this document.
  613. this.cleanUp()
  614. }
  615. private applyOpsToRanges(ops: AnyOperation[], msg?: Message) {
  616. let old_id_seed
  617. let track_changes_as = null
  618. const remote_op = msg != null
  619. if (remote_op && msg?.meta.tc) {
  620. old_id_seed = this.ranges!.getIdSeed()
  621. this.ranges!.setIdSeed(msg.meta.tc)
  622. track_changes_as = msg.meta.user_id
  623. } else if (!remote_op && this.track_changes_as != null) {
  624. track_changes_as = this.track_changes_as
  625. }
  626. this.ranges!.track_changes = track_changes_as != null
  627. for (const op of this.filterOps(ops)) {
  628. this.ranges!.applyOp(op, { user_id: track_changes_as })
  629. }
  630. if (old_id_seed != null) {
  631. this.ranges!.setIdSeed(old_id_seed)
  632. }
  633. if (remote_op) {
  634. // With remote ops, the editor hasn't been updated when we receive this
  635. // op, so defer updating track changes until it has
  636. return window.setTimeout(() => this.emit('ranges:dirty'))
  637. } else {
  638. return this.emit('ranges:dirty')
  639. }
  640. }
  641. private catchUpRanges(
  642. changes: Change<EditOperation>[],
  643. comments: Change<CommentOperation>[]
  644. ) {
  645. // We've just been given the current server's ranges, but need to apply any local ops we have.
  646. // Reset to the server state then apply our local ops again.
  647. if (changes == null) {
  648. changes = []
  649. }
  650. if (comments == null) {
  651. comments = []
  652. }
  653. this.emit('ranges:clear')
  654. this.ranges!.changes = changes
  655. this.ranges!.comments = comments
  656. this.ranges!.track_changes = this.doc?.track_changes
  657. for (const op of this.filterOps(this.doc?.getInflightOp() || [])) {
  658. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.inflight)
  659. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  660. }
  661. for (const op of this.filterOps(this.doc?.getPendingOp() || [])) {
  662. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.pending)
  663. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  664. }
  665. return this.emit('ranges:redraw')
  666. }
  667. private filterOps(ops: AnyOperation[]) {
  668. // Read-only token users can't see/edit comment, so we filter out comment
  669. // ops to avoid highlighting comment ranges.
  670. if (window.isRestrictedTokenMember) {
  671. return ops.filter(op => !isCommentOperation(op))
  672. } else {
  673. return ops
  674. }
  675. }
  676. }