document-container.ts 20 KB

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