document-container.ts 21 KB

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