document.ts 20 KB

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