document-container.ts 21 KB

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