document.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. join(callback?: JoinCallback) {
  193. this.wantToBeJoined = true
  194. this.cancelLeave()
  195. if (this.connected) {
  196. this.joinDoc(callback)
  197. } else if (callback) {
  198. this.joinCallbacks.push(callback)
  199. }
  200. }
  201. leave(callback?: LeaveCallback) {
  202. this.flush() // force an immediate flush when leaving document
  203. this.wantToBeJoined = false
  204. this.cancelJoin()
  205. if (this.doc?.hasBufferedOps()) {
  206. debugConsole.log(
  207. '[leave] Doc has buffered ops, pushing callback for later'
  208. )
  209. if (callback) {
  210. this.leaveCallbacks.push(callback)
  211. }
  212. } else if (!this.connected) {
  213. debugConsole.log('[leave] Not connected, returning now')
  214. callback?.()
  215. } else {
  216. debugConsole.log('[leave] Leaving now')
  217. this.leaveDoc(callback)
  218. }
  219. }
  220. flush() {
  221. return this.doc?.flushPendingOps()
  222. }
  223. chaosMonkey(line = 0, char = 'a') {
  224. const orig = char
  225. let copy: string | null = null
  226. let pos = 0
  227. const timer = () => {
  228. if (copy == null || !copy.length) {
  229. copy = orig.slice() + ' ' + new Date() + '\n'
  230. line += Math.random() > 0.1 ? 1 : -2
  231. if (line < 0) {
  232. line = 0
  233. }
  234. pos = 0
  235. }
  236. char = copy[0]
  237. copy = copy.slice(1)
  238. if (this.cm6) {
  239. this.cm6.view.dispatch({
  240. changes: {
  241. from: Math.min(pos, this.cm6.view.state.doc.length),
  242. insert: char,
  243. },
  244. })
  245. }
  246. pos += 1
  247. this.chaosMonkeyTimer = window.setTimeout(
  248. timer,
  249. 100 + (Math.random() < 0.1 ? 1000 : 0)
  250. )
  251. }
  252. timer()
  253. }
  254. clearChaosMonkey() {
  255. const timer = this.chaosMonkeyTimer
  256. if (timer) {
  257. this.chaosMonkeyTimer = null
  258. window.clearTimeout(timer)
  259. }
  260. }
  261. pollSavedStatus() {
  262. // returns false if doc has ops waiting to be acknowledged or
  263. // sent that haven't changed since the last time we checked.
  264. // Otherwise returns true.
  265. let saved
  266. const inflightOp = this.getInflightOp()
  267. const pendingOp = this.getPendingOp()
  268. const recentAck = this.getRecentAck()
  269. const pendingOpSize = pendingOp ? getShareJsOpSize(pendingOp) : 0
  270. if (inflightOp == null && pendingOp == null) {
  271. // There's nothing going on, this is OK.
  272. saved = true
  273. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  274. } else if (inflightOp && inflightOp === this.oldInflightOp) {
  275. // The same inflight op has been sitting unacked since we
  276. // last checked, this is bad.
  277. saved = false
  278. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  279. } else if (
  280. pendingOp != null &&
  281. recentAck &&
  282. pendingOpSize < MAX_PENDING_OP_SIZE
  283. ) {
  284. // There is an op waiting to go to server but it is small and
  285. // within the flushDelay, this is OK for now.
  286. saved = true
  287. debugConsole.log(
  288. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  289. pendingOp,
  290. pendingOpSize
  291. )
  292. } else {
  293. // In any other situation, assume the document is unsaved.
  294. saved = false
  295. debugConsole.log(
  296. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  297. inflightOp != null
  298. }, pendingOp?: ${pendingOp != null})`
  299. )
  300. }
  301. this.oldInflightOp = inflightOp
  302. return saved
  303. }
  304. private cancelLeave() {
  305. this.leaveCallbacks = []
  306. }
  307. private cancelJoin() {
  308. this.joinCallbacks = []
  309. }
  310. private onUpdateApplied(update: Update) {
  311. this.eventLog.pushEvent('received-update', {
  312. doc_id: this.doc_id,
  313. remote_doc_id: update?.doc,
  314. wantToBeJoined: this.wantToBeJoined,
  315. update,
  316. hasDoc: !!this.doc,
  317. })
  318. if (update?.doc === this.doc_id && this.doc != null) {
  319. this.eventLog.pushEvent('received-update:processing', {
  320. update,
  321. })
  322. // FIXME: change this back to processUpdateFromServer when redis fixed
  323. this.doc.processUpdateFromServerInOrder(update)
  324. if (!this.wantToBeJoined) {
  325. return this.leave()
  326. }
  327. }
  328. }
  329. private onDisconnect() {
  330. debugConsole.log('[onDisconnect] disconnecting')
  331. this.connected = false
  332. this.joined = false
  333. return this.doc != null
  334. ? this.doc.updateConnectionState('disconnected')
  335. : undefined
  336. }
  337. private onReconnect = () => {
  338. debugConsole.log('[onReconnect] reconnected (joined project)')
  339. this.eventLog.pushEvent('reconnected:afterJoinProject')
  340. this.connected = true
  341. if (this.wantToBeJoined || this.doc?.hasBufferedOps()) {
  342. debugConsole.log(
  343. `[onReconnect] Rejoining (wantToBeJoined: ${
  344. this.wantToBeJoined
  345. } OR hasBufferedOps: ${this.doc?.hasBufferedOps()})`
  346. )
  347. this.joinDoc((error?: Error) => {
  348. if (error) {
  349. this.onError(error)
  350. return
  351. }
  352. this.doc?.updateConnectionState('ok')
  353. this.doc?.flushPendingOps()
  354. this.callJoinCallbacks()
  355. })
  356. }
  357. }
  358. private callJoinCallbacks() {
  359. for (const callback of this.joinCallbacks) {
  360. callback()
  361. }
  362. this.joinCallbacks = []
  363. }
  364. private joinDoc(callback?: JoinCallback) {
  365. if (this.doc) {
  366. this.eventLog.pushEvent('joinDoc:existing', {
  367. doc_id: this.doc_id,
  368. version: this.doc.getVersion(),
  369. })
  370. return this.socket.emit(
  371. 'joinDoc',
  372. this.doc_id,
  373. this.doc.getVersion(),
  374. { encodeRanges: true },
  375. (error, docLines, version, updates, ranges) => {
  376. if (error) {
  377. callback?.(error)
  378. return
  379. }
  380. this.joined = true
  381. this.doc?.catchUp(updates)
  382. this.decodeRanges(ranges)
  383. this.catchUpRanges(ranges?.changes, ranges?.comments)
  384. callback?.()
  385. }
  386. )
  387. } else {
  388. this.eventLog.pushEvent('joinDoc:new', {
  389. doc_id: this.doc_id,
  390. })
  391. this.socket.emit(
  392. 'joinDoc',
  393. this.doc_id,
  394. { encodeRanges: true },
  395. (error, docLines, version, updates, ranges) => {
  396. if (error) {
  397. callback?.(error)
  398. return
  399. }
  400. this.joined = true
  401. this.eventLog.pushEvent('joinDoc:inited', {
  402. doc_id: this.doc_id,
  403. version,
  404. })
  405. this.doc = new ShareJsDoc(
  406. this.doc_id,
  407. docLines,
  408. version,
  409. this.socket,
  410. this.globalEditorWatchdogManager,
  411. this.ideEventEmitter,
  412. this.eventLog
  413. )
  414. this.decodeRanges(ranges)
  415. this.ranges = new RangesTracker(ranges?.changes, ranges?.comments)
  416. this.bindToShareJsDocEvents()
  417. callback?.()
  418. }
  419. )
  420. }
  421. }
  422. private decodeRanges(ranges: RangesTracker) {
  423. try {
  424. if (ranges.changes) {
  425. for (const change of ranges.changes) {
  426. if (isInsertOperation(change.op)) {
  427. change.op.i = decodeUtf8(change.op.i)
  428. }
  429. if (isDeleteOperation(change.op)) {
  430. change.op.d = decodeUtf8(change.op.d)
  431. }
  432. }
  433. }
  434. return (() => {
  435. if (!ranges.comments) {
  436. return []
  437. }
  438. return ranges.comments.map((comment: Change<CommentOperation>) =>
  439. comment.op.c != null
  440. ? (comment.op.c = decodeUtf8(comment.op.c))
  441. : undefined
  442. )
  443. })()
  444. } catch (err) {
  445. debugConsole.error(err)
  446. }
  447. }
  448. private leaveDoc(callback?: LeaveCallback) {
  449. this.eventLog.pushEvent('leaveDoc', {
  450. doc_id: this.doc_id,
  451. })
  452. debugConsole.log('[leaveDoc] Sending leaveDoc request')
  453. this.socket.emit('leaveDoc', this.doc_id, error => {
  454. if (error) {
  455. callback?.(error)
  456. return
  457. }
  458. this.joined = false
  459. for (const leaveCallback of this.leaveCallbacks) {
  460. debugConsole.log('[_leaveDoc] Calling buffered callback', leaveCallback)
  461. leaveCallback(error)
  462. }
  463. this.leaveCallbacks = []
  464. callback?.()
  465. })
  466. }
  467. cleanUp() {
  468. // if we arrive here from _onError the pending and inflight ops will have been cleared
  469. if (this.hasBufferedOps()) {
  470. debugConsole.log(
  471. `[cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  472. )
  473. return // return immediately, do not unbind from events
  474. } else {
  475. this.emit('detach', this.doc_id)
  476. }
  477. this.unBindFromEditorEvents()
  478. this.unBindFromSocketEvents()
  479. }
  480. private bindToShareJsDocEvents() {
  481. if (!this.doc) {
  482. return
  483. }
  484. this.doc.on('error', (error: Error, meta: ErrorMetadata) =>
  485. this.onError(error, meta)
  486. )
  487. this.doc.on('externalUpdate', (update: Update) => {
  488. this.eventLog.pushEvent('externalUpdate', { doc_id: this.doc_id })
  489. return this.trigger('externalUpdate', update)
  490. })
  491. this.doc.on('remoteop', (...ops: AnyOperation[]) => {
  492. this.eventLog.pushEvent('remoteop', { doc_id: this.doc_id })
  493. return this.trigger('remoteop', ...ops)
  494. })
  495. this.doc.on('op:sent', (op: AnyOperation) => {
  496. this.eventLog.pushEvent('op:sent', {
  497. doc_id: this.doc_id,
  498. op,
  499. })
  500. return this.trigger('op:sent')
  501. })
  502. this.doc.on('op:acknowledged', (op: AnyOperation) => {
  503. this.eventLog.pushEvent('op:acknowledged', {
  504. doc_id: this.doc_id,
  505. op,
  506. })
  507. this.ideEventEmitter.emit('ide:opAcknowledged', {
  508. doc_id: this.doc_id,
  509. op,
  510. })
  511. return this.trigger('op:acknowledged')
  512. })
  513. this.doc.on('op:timeout', (op: AnyOperation) => {
  514. this.eventLog.pushEvent('op:timeout', {
  515. doc_id: this.doc_id,
  516. op,
  517. })
  518. this.trigger('op:timeout')
  519. return this.onError(new Error('op timed out'))
  520. })
  521. this.doc.on(
  522. 'flush',
  523. (inflightOp: AnyOperation, pendingOp: AnyOperation, version: Version) => {
  524. return this.eventLog.pushEvent('flush', {
  525. doc_id: this.doc_id,
  526. inflightOp,
  527. pendingOp,
  528. v: version,
  529. })
  530. }
  531. )
  532. let docChangedTimeout: number | null = null
  533. this.doc.on(
  534. 'change',
  535. (ops: AnyOperation[], oldSnapshot: any, msg: Message) => {
  536. this.applyOpsToRanges(ops, msg)
  537. if (docChangedTimeout) {
  538. window.clearTimeout(docChangedTimeout)
  539. }
  540. docChangedTimeout = window.setTimeout(() => {
  541. window.dispatchEvent(
  542. new CustomEvent('doc:changed', { detail: { id: this.doc_id } })
  543. )
  544. this.ideEventEmitter.emit('doc:changed', { doc_id: this.doc_id })
  545. }, 50)
  546. }
  547. )
  548. this.doc.on('flipped_pending_to_inflight', () => {
  549. return this.trigger('flipped_pending_to_inflight')
  550. })
  551. let docSavedTimeout: number | null
  552. this.doc.on('saved', () => {
  553. if (docSavedTimeout) {
  554. window.clearTimeout(docSavedTimeout)
  555. }
  556. docSavedTimeout = window.setTimeout(() => {
  557. window.dispatchEvent(
  558. new CustomEvent('doc:saved', { detail: { id: this.doc_id } })
  559. )
  560. this.ideEventEmitter.emit('doc:saved', { doc_id: this.doc_id })
  561. }, 50)
  562. })
  563. }
  564. private onError(
  565. error: Error,
  566. meta: ErrorMetadata = {},
  567. editorContent?: string
  568. ) {
  569. meta.doc_id = this.doc_id
  570. debugConsole.log('ShareJS error', error, meta)
  571. if (error.message === 'no project_id found on client') {
  572. debugConsole.log('ignoring error, will wait to join project')
  573. return
  574. }
  575. if (this.doc) {
  576. this.doc.clearInflightAndPendingOps()
  577. }
  578. this.trigger('error', error, meta, editorContent)
  579. // The clean-up should run after the error is triggered because the error triggers a
  580. // disconnect. If we run the clean-up first, we remove our event handlers and miss
  581. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  582. // This could interfere with the new connection of a new instance of this document.
  583. this.cleanUp()
  584. }
  585. private applyOpsToRanges(ops: AnyOperation[], msg?: Message) {
  586. let old_id_seed
  587. let track_changes_as = null
  588. const remote_op = msg != null
  589. if (remote_op && msg?.meta.tc) {
  590. old_id_seed = this.ranges.getIdSeed()
  591. this.ranges.setIdSeed(msg.meta.tc)
  592. track_changes_as = msg.meta.user_id
  593. } else if (!remote_op && this.track_changes_as != null) {
  594. track_changes_as = this.track_changes_as
  595. }
  596. this.ranges.track_changes = track_changes_as != null
  597. for (const op of this.filterOps(ops)) {
  598. this.ranges.applyOp(op, { user_id: track_changes_as })
  599. }
  600. if (old_id_seed != null) {
  601. this.ranges.setIdSeed(old_id_seed)
  602. }
  603. if (remote_op) {
  604. // With remote ops, the editor hasn't been updated when we receive this
  605. // op, so defer updating track changes until it has
  606. return window.setTimeout(() => this.emit('ranges:dirty'))
  607. } else {
  608. return this.emit('ranges:dirty')
  609. }
  610. }
  611. private catchUpRanges(changes: Change[], comments: CommentOperation[]) {
  612. // We've just been given the current server's ranges, but need to apply any local ops we have.
  613. // Reset to the server state then apply our local ops again.
  614. if (changes == null) {
  615. changes = []
  616. }
  617. if (comments == null) {
  618. comments = []
  619. }
  620. this.emit('ranges:clear')
  621. this.ranges.changes = changes
  622. this.ranges.comments = comments
  623. this.ranges.track_changes = this.doc?.track_changes
  624. for (const op of this.filterOps(this.doc?.getInflightOp() || [])) {
  625. this.ranges.setIdSeed(this.doc?.track_changes_id_seeds?.inflight)
  626. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  627. }
  628. for (const op of this.filterOps(this.doc?.getPendingOp() || [])) {
  629. this.ranges.setIdSeed(this.doc?.track_changes_id_seeds?.pending)
  630. this.ranges.applyOp(op, { user_id: this.track_changes_as })
  631. }
  632. return this.emit('ranges:redraw')
  633. }
  634. private filterOps(ops: AnyOperation[]) {
  635. // Read-only token users can't see/edit comment, so we filter out comment
  636. // ops to avoid highlighting comment ranges.
  637. if (window.isRestrictedTokenMember) {
  638. return ops.filter(op => !isCommentOperation(op))
  639. } else {
  640. return ops
  641. }
  642. }
  643. }