document-container.ts 21 KB

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