document.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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. private readonly detachDoc: (docId: string, doc: Document) => void
  94. ) {
  95. super()
  96. this.connected = this.socket.socket.connected
  97. this.bindToEditorEvents()
  98. this.bindToSocketEvents()
  99. }
  100. attachToCM6(cm6: EditorFacade) {
  101. this.cm6 = cm6
  102. if (this.doc) {
  103. this.doc.attachToCM6(this.cm6)
  104. }
  105. if (this.cm6) {
  106. this.cm6.on('change', this.checkConsistency)
  107. }
  108. }
  109. detachFromCM6() {
  110. if (this.doc) {
  111. this.doc.detachFromCM6()
  112. }
  113. if (this.cm6) {
  114. this.cm6.off('change', this.checkConsistency)
  115. }
  116. delete this.cm6
  117. this.clearChaosMonkey()
  118. if (this.doc) {
  119. this.ideEventEmitter.emit('document:closed', this.doc)
  120. }
  121. }
  122. submitOp(...ops: AnyOperation[]) {
  123. this.doc?.submitOp(ops)
  124. }
  125. private checkConsistency = (editor: EditorFacade) => {
  126. // We've been seeing a lot of errors when I think there shouldn't be
  127. // any, which may be related to this check happening before the change is
  128. // applied. If we use a timeout, hopefully we can reduce this.
  129. window.setTimeout(() => {
  130. const editorValue = editor?.getValue()
  131. const sharejsValue = this.doc?.getSnapshot()
  132. if (editorValue !== sharejsValue) {
  133. return this.onError(
  134. new Error('Editor text does not match server text'),
  135. {},
  136. editorValue
  137. )
  138. }
  139. }, 0)
  140. }
  141. getSnapshot() {
  142. return this.doc?.getSnapshot()
  143. }
  144. getType() {
  145. return this.doc?.getType()
  146. }
  147. getInflightOp(): ShareJsOperation | undefined {
  148. return this.doc?.getInflightOp()
  149. }
  150. getPendingOp(): ShareJsOperation | undefined {
  151. return this.doc?.getPendingOp()
  152. }
  153. getRecentAck() {
  154. return this.doc?.getRecentAck()
  155. }
  156. hasBufferedOps() {
  157. return this.doc?.hasBufferedOps()
  158. }
  159. setTrackingChanges(track_changes: boolean) {
  160. if (this.doc) {
  161. this.doc.track_changes = track_changes
  162. }
  163. }
  164. getTrackingChanges() {
  165. return !!this.doc?.track_changes
  166. }
  167. setTrackChangesIdSeeds(id_seeds: TrackChangesIdSeeds) {
  168. if (this.doc) {
  169. this.doc.track_changes_id_seeds = id_seeds
  170. }
  171. }
  172. private onUpdateAppliedHandler = (update: any) => this.onUpdateApplied(update)
  173. private onErrorHandler = (error: Error, message: ErrorMetadata) => {
  174. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  175. // sure that message.doc_id exists.
  176. if (message.doc_id !== this.doc_id) {
  177. // This error is for another doc. Do not action it. We could open
  178. // a modal that has the wrong context on it.
  179. return
  180. }
  181. this.onError(error, message)
  182. }
  183. private onDisconnectHandler = () => this.onDisconnect()
  184. private bindToSocketEvents() {
  185. this.socket.on('otUpdateApplied', this.onUpdateAppliedHandler)
  186. this.socket.on('otUpdateError', this.onErrorHandler)
  187. return this.socket.on('disconnect', this.onDisconnectHandler)
  188. }
  189. private unBindFromSocketEvents() {
  190. this.socket.removeListener('otUpdateApplied', this.onUpdateAppliedHandler)
  191. this.socket.removeListener('otUpdateError', this.onErrorHandler)
  192. return this.socket.removeListener('disconnect', this.onDisconnectHandler)
  193. }
  194. private bindToEditorEvents() {
  195. this.ideEventEmitter.on('project:joined', this.onReconnect)
  196. }
  197. private unBindFromEditorEvents() {
  198. this.ideEventEmitter.off('project:joined', this.onReconnect)
  199. }
  200. leaveAndCleanUp(cb?: (error?: Error) => void) {
  201. return this.leave((error?: Error) => {
  202. this.cleanUp()
  203. if (cb) cb(error)
  204. })
  205. }
  206. leaveAndCleanUpPromise() {
  207. return new Promise<void>((resolve, reject) => {
  208. this.leaveAndCleanUp((error?: Error) => {
  209. if (error) {
  210. reject(error)
  211. } else {
  212. resolve()
  213. }
  214. })
  215. })
  216. }
  217. join(callback?: JoinCallback) {
  218. this.wantToBeJoined = true
  219. this.cancelLeave()
  220. if (this.connected) {
  221. this.joinDoc(callback)
  222. } else if (callback) {
  223. this.joinCallbacks.push(callback)
  224. }
  225. }
  226. leave(callback?: LeaveCallback) {
  227. this.flush() // force an immediate flush when leaving document
  228. this.wantToBeJoined = false
  229. this.cancelJoin()
  230. if (this.doc?.hasBufferedOps()) {
  231. debugConsole.log(
  232. '[leave] Doc has buffered ops, pushing callback for later'
  233. )
  234. if (callback) {
  235. this.leaveCallbacks.push(callback)
  236. }
  237. } else if (!this.connected) {
  238. debugConsole.log('[leave] Not connected, returning now')
  239. callback?.()
  240. } else {
  241. debugConsole.log('[leave] Leaving now')
  242. this.leaveDoc(callback)
  243. }
  244. }
  245. flush() {
  246. return this.doc?.flushPendingOps()
  247. }
  248. chaosMonkey(line = 0, char = 'a') {
  249. const orig = char
  250. let copy: string | null = null
  251. let pos = 0
  252. const timer = () => {
  253. if (copy == null || !copy.length) {
  254. copy = orig.slice() + ' ' + new Date() + '\n'
  255. line += Math.random() > 0.1 ? 1 : -2
  256. if (line < 0) {
  257. line = 0
  258. }
  259. pos = 0
  260. }
  261. char = copy[0]
  262. copy = copy.slice(1)
  263. if (this.cm6) {
  264. this.cm6.view.dispatch({
  265. changes: {
  266. from: Math.min(pos, this.cm6.view.state.doc.length),
  267. insert: char,
  268. },
  269. })
  270. }
  271. pos += 1
  272. this.chaosMonkeyTimer = window.setTimeout(
  273. timer,
  274. 100 + (Math.random() < 0.1 ? 1000 : 0)
  275. )
  276. }
  277. timer()
  278. }
  279. clearChaosMonkey() {
  280. const timer = this.chaosMonkeyTimer
  281. if (timer) {
  282. this.chaosMonkeyTimer = null
  283. window.clearTimeout(timer)
  284. }
  285. }
  286. pollSavedStatus() {
  287. // returns false if doc has ops waiting to be acknowledged or
  288. // sent that haven't changed since the last time we checked.
  289. // Otherwise returns true.
  290. let saved
  291. const inflightOp = this.getInflightOp()
  292. const pendingOp = this.getPendingOp()
  293. const recentAck = this.getRecentAck()
  294. const pendingOpSize = pendingOp ? getShareJsOpSize(pendingOp) : 0
  295. if (inflightOp == null && pendingOp == null) {
  296. // There's nothing going on, this is OK.
  297. saved = true
  298. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  299. } else if (inflightOp && inflightOp === this.oldInflightOp) {
  300. // The same inflight op has been sitting unacked since we
  301. // last checked, this is bad.
  302. saved = false
  303. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  304. } else if (
  305. pendingOp != null &&
  306. recentAck &&
  307. pendingOpSize < MAX_PENDING_OP_SIZE
  308. ) {
  309. // There is an op waiting to go to server but it is small and
  310. // within the flushDelay, this is OK for now.
  311. saved = true
  312. debugConsole.log(
  313. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  314. pendingOp,
  315. pendingOpSize
  316. )
  317. } else {
  318. // In any other situation, assume the document is unsaved.
  319. saved = false
  320. debugConsole.log(
  321. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  322. inflightOp != null
  323. }, pendingOp?: ${pendingOp != null})`
  324. )
  325. }
  326. this.oldInflightOp = inflightOp
  327. return saved
  328. }
  329. private cancelLeave() {
  330. this.leaveCallbacks = []
  331. }
  332. private cancelJoin() {
  333. this.joinCallbacks = []
  334. }
  335. private onUpdateApplied(update: Update) {
  336. this.eventLog.pushEvent('received-update', {
  337. doc_id: this.doc_id,
  338. remote_doc_id: update?.doc,
  339. wantToBeJoined: this.wantToBeJoined,
  340. update,
  341. hasDoc: !!this.doc,
  342. })
  343. if (update?.doc === this.doc_id && this.doc != null) {
  344. this.eventLog.pushEvent('received-update:processing', {
  345. update,
  346. })
  347. // FIXME: change this back to processUpdateFromServer when redis fixed
  348. this.doc.processUpdateFromServerInOrder(update)
  349. if (!this.wantToBeJoined) {
  350. return this.leave()
  351. }
  352. }
  353. }
  354. private onDisconnect() {
  355. debugConsole.log('[onDisconnect] disconnecting')
  356. this.connected = false
  357. this.joined = false
  358. return this.doc != null
  359. ? this.doc.updateConnectionState('disconnected')
  360. : undefined
  361. }
  362. private onReconnect = () => {
  363. debugConsole.log('[onReconnect] reconnected (joined project)')
  364. this.eventLog.pushEvent('reconnected:afterJoinProject')
  365. this.connected = true
  366. if (this.wantToBeJoined || this.doc?.hasBufferedOps()) {
  367. debugConsole.log(
  368. `[onReconnect] Rejoining (wantToBeJoined: ${
  369. this.wantToBeJoined
  370. } OR hasBufferedOps: ${this.doc?.hasBufferedOps()})`
  371. )
  372. this.joinDoc((error?: Error) => {
  373. if (error) {
  374. this.onError(error)
  375. return
  376. }
  377. this.doc?.updateConnectionState('ok')
  378. this.doc?.flushPendingOps()
  379. this.callJoinCallbacks()
  380. })
  381. }
  382. }
  383. private callJoinCallbacks() {
  384. for (const callback of this.joinCallbacks) {
  385. callback()
  386. }
  387. this.joinCallbacks = []
  388. }
  389. private joinDoc(callback?: JoinCallback) {
  390. if (this.doc) {
  391. this.eventLog.pushEvent('joinDoc:existing', {
  392. doc_id: this.doc_id,
  393. version: this.doc.getVersion(),
  394. })
  395. return this.socket.emit(
  396. 'joinDoc',
  397. this.doc_id,
  398. this.doc.getVersion(),
  399. { encodeRanges: true },
  400. (error, docLines, version, updates, ranges) => {
  401. if (error) {
  402. callback?.(error)
  403. return
  404. }
  405. this.joined = true
  406. this.doc?.catchUp(updates)
  407. this.decodeRanges(ranges)
  408. this.catchUpRanges(ranges?.changes, ranges?.comments)
  409. callback?.()
  410. }
  411. )
  412. } else {
  413. this.eventLog.pushEvent('joinDoc:new', {
  414. doc_id: this.doc_id,
  415. })
  416. this.socket.emit(
  417. 'joinDoc',
  418. this.doc_id,
  419. { encodeRanges: true },
  420. (error, docLines, version, updates, ranges) => {
  421. if (error) {
  422. callback?.(error)
  423. return
  424. }
  425. this.joined = true
  426. this.eventLog.pushEvent('joinDoc:inited', {
  427. doc_id: this.doc_id,
  428. version,
  429. })
  430. this.doc = new ShareJsDoc(
  431. this.doc_id,
  432. docLines,
  433. version,
  434. this.socket,
  435. this.globalEditorWatchdogManager,
  436. this.ideEventEmitter,
  437. this.eventLog
  438. )
  439. this.decodeRanges(ranges)
  440. this.ranges = new RangesTracker(ranges?.changes, ranges?.comments)
  441. this.bindToShareJsDocEvents()
  442. callback?.()
  443. }
  444. )
  445. }
  446. }
  447. private decodeRanges(ranges: RangesTracker) {
  448. try {
  449. if (ranges.changes) {
  450. for (const change of ranges.changes) {
  451. if (isInsertOperation(change.op)) {
  452. change.op.i = decodeUtf8(change.op.i)
  453. }
  454. if (isDeleteOperation(change.op)) {
  455. change.op.d = decodeUtf8(change.op.d)
  456. }
  457. }
  458. }
  459. return (() => {
  460. if (!ranges.comments) {
  461. return []
  462. }
  463. return ranges.comments.map((comment: Change<CommentOperation>) =>
  464. comment.op.c != null
  465. ? (comment.op.c = decodeUtf8(comment.op.c))
  466. : undefined
  467. )
  468. })()
  469. } catch (err) {
  470. debugConsole.error(err)
  471. }
  472. }
  473. private leaveDoc(callback?: LeaveCallback) {
  474. this.eventLog.pushEvent('leaveDoc', {
  475. doc_id: this.doc_id,
  476. })
  477. debugConsole.log('[leaveDoc] Sending leaveDoc request')
  478. this.socket.emit('leaveDoc', this.doc_id, error => {
  479. if (error) {
  480. callback?.(error)
  481. return
  482. }
  483. this.joined = false
  484. for (const leaveCallback of this.leaveCallbacks) {
  485. debugConsole.log('[_leaveDoc] Calling buffered callback', leaveCallback)
  486. leaveCallback(error)
  487. }
  488. this.leaveCallbacks = []
  489. callback?.()
  490. })
  491. }
  492. cleanUp() {
  493. // if we arrive here from _onError the pending and inflight ops will have been cleared
  494. if (this.hasBufferedOps()) {
  495. debugConsole.log(
  496. `[cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  497. )
  498. return // return immediately, do not unbind from events
  499. }
  500. this.detachDoc(this.doc_id, this)
  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. }