document.ts 20 KB

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