document-container.ts 21 KB

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