index.cjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /**
  2. * The purpose of this class is to track a set of inserts and deletes to a document, like
  3. * track changes in Word. We store these as a set of ShareJs style ranges:
  4. * {i: "foo", p: 42} # Insert 'foo' at offset 42
  5. * {d: "bar", p: 37} # Delete 'bar' at offset 37
  6. * We only track the inserts and deletes, not the whole document, but by being given all
  7. * updates that are applied to a document, we can update these appropriately.
  8. *
  9. * Note that the set of inserts and deletes we store applies to the document as-is at the moment.
  10. * So inserts correspond to text which is in the document, while deletes correspond to text which
  11. * is no longer there, so their lengths do not affect the position of later offsets.
  12. * E.g.
  13. * this is the current text of the document
  14. * |-----| |
  15. * {i: "current ", p:12} -^ ^- {d: "old ", p: 31}
  16. *
  17. * Track changes rules (should be consistent with Word):
  18. * * When text is inserted at a delete, the text goes to the left of the delete
  19. * I.e. "foo|bar" -> "foobaz|bar", where | is the delete, and 'baz' is inserted
  20. * * Deleting content flagged as 'inserted' does not create a new delete marker, it only
  21. * removes the insert marker. E.g.
  22. * * "abdefghijkl" -> "abfghijkl" when 'de' is deleted. No delete marker added
  23. * |---| <- inserted |-| <- inserted
  24. * * Deletes overlapping regular text and inserted text will insert a delete marker for the
  25. * regular text:
  26. * "abcdefghijkl" -> "abcdejkl" when 'fghi' is deleted
  27. * |----| |--||
  28. * ^- inserted 'bcdefg' \ ^- deleted 'hi'
  29. * \--inserted 'bcde'
  30. * * Deletes overlapping other deletes are merged. E.g.
  31. * "abcghijkl" -> "ahijkl" when 'bcg is deleted'
  32. * | <- delete 'def' | <- delete 'bcdefg'
  33. * * Deletes by another user will consume deletes by the first user
  34. * * Inserts by another user will not combine with inserts by the first user. If they are in the
  35. * middle of a previous insert by the first user, the original insert will be split into two.
  36. */
  37. class RangesTracker {
  38. constructor(changes, comments) {
  39. if (changes == null) {
  40. changes = []
  41. }
  42. this.changes = changes
  43. if (comments == null) {
  44. comments = []
  45. }
  46. this.comments = comments
  47. this.track_changes = false
  48. this.id_seed = RangesTracker.generateIdSeed()
  49. this.id_increment = 0
  50. this._dirtyState = {
  51. comment: {
  52. moved: {},
  53. removed: {},
  54. added: {},
  55. },
  56. change: {
  57. moved: {},
  58. removed: {},
  59. added: {},
  60. },
  61. }
  62. }
  63. getIdSeed() {
  64. return this.id_seed
  65. }
  66. setIdSeed(seed) {
  67. this.id_seed = seed
  68. this.id_increment = 0
  69. }
  70. static generateIdSeed() {
  71. // Generate a the first 18 characters of Mongo ObjectId, leaving 6 for the increment part
  72. // Reference: https://github.com/dreampulse/ObjectId.js/blob/master/src/main/javascript/Objectid.js
  73. const pid = Math.floor(Math.random() * 32767).toString(16)
  74. const machine = Math.floor(Math.random() * 16777216).toString(16)
  75. const timestamp = Math.floor(new Date().valueOf() / 1000).toString(16)
  76. return (
  77. '00000000'.substr(0, 8 - timestamp.length) +
  78. timestamp +
  79. '000000'.substr(0, 6 - machine.length) +
  80. machine +
  81. '0000'.substr(0, 4 - pid.length) +
  82. pid
  83. )
  84. }
  85. static generateId() {
  86. return this.generateIdSeed() + '000001'
  87. }
  88. newId() {
  89. this.id_increment++
  90. const increment = this.id_increment.toString(16)
  91. const id =
  92. this.id_seed + '000000'.substr(0, 6 - increment.length) + increment
  93. return id
  94. }
  95. getComment(commentId) {
  96. let comment = null
  97. for (const c of this.comments) {
  98. if (c.id === commentId) {
  99. comment = c
  100. break
  101. }
  102. }
  103. return comment
  104. }
  105. removeCommentId(commentId) {
  106. const comment = this.getComment(commentId)
  107. if (comment == null) {
  108. return
  109. }
  110. this.comments = this.comments.filter(c => c.id !== commentId)
  111. this._markAsDirty(comment, 'comment', 'removed')
  112. }
  113. moveCommentId(commentId, position, text) {
  114. for (const comment of this.comments) {
  115. if (comment.id === commentId) {
  116. comment.op.p = position
  117. comment.op.c = text
  118. this._markAsDirty(comment, 'comment', 'moved')
  119. }
  120. }
  121. }
  122. getChange(changeId) {
  123. let change = null
  124. for (const c of this.changes) {
  125. if (c.id === changeId) {
  126. change = c
  127. break
  128. }
  129. }
  130. return change
  131. }
  132. getChanges(ids) {
  133. const idSet = new Set(ids)
  134. return this.changes.filter(change => idSet.has(change.id))
  135. }
  136. removeChangeId(changeId) {
  137. const change = this.getChange(changeId)
  138. if (change == null) {
  139. return
  140. }
  141. this._removeChange(change)
  142. }
  143. removeChangeIds(ids) {
  144. if (ids == null || ids.length === 0) {
  145. return
  146. }
  147. const idSet = new Set(ids)
  148. const remainingChanges = []
  149. for (const change of this.changes) {
  150. if (idSet.has(change.id)) {
  151. this._markAsDirty(change, 'change', 'removed')
  152. } else {
  153. remainingChanges.push(change)
  154. }
  155. }
  156. this.changes = remainingChanges
  157. }
  158. validate(text) {
  159. let content
  160. for (const change of this.changes) {
  161. if (change.op.i != null) {
  162. content = text.slice(change.op.p, change.op.p + change.op.i.length)
  163. if (content !== change.op.i) {
  164. throw new Error('insertion does not match text in document')
  165. }
  166. }
  167. }
  168. for (const comment of this.comments) {
  169. content = text.slice(comment.op.p, comment.op.p + comment.op.c.length)
  170. if (content !== comment.op.c) {
  171. throw new Error('comment does not match text in document')
  172. }
  173. }
  174. }
  175. applyOp(op, metadata) {
  176. if (metadata == null) {
  177. metadata = {}
  178. }
  179. if (metadata.ts == null) {
  180. metadata.ts = new Date()
  181. }
  182. // Apply an op that has been applied to the document to our changes to keep them up to date
  183. if (op.i != null) {
  184. this.applyInsertToChanges(op, metadata)
  185. this.applyInsertToComments(op)
  186. } else if (op.d != null) {
  187. this.applyDeleteToChanges(op, metadata)
  188. this.applyDeleteToComments(op)
  189. } else if (op.c != null) {
  190. this.addComment(op, metadata)
  191. } else {
  192. throw new Error('unknown op type')
  193. }
  194. }
  195. applyOps(ops, metadata) {
  196. if (metadata == null) {
  197. metadata = {}
  198. }
  199. for (const op of ops) {
  200. this.applyOp(op, metadata)
  201. }
  202. }
  203. addComment(op, metadata) {
  204. const existing = this.getComment(op.t)
  205. if (existing != null) {
  206. this.moveCommentId(op.t, op.p, op.c)
  207. } else {
  208. let comment
  209. this.comments.push(
  210. (comment = {
  211. id: op.t || this.newId(),
  212. op: {
  213. // Copy because we'll modify in place
  214. c: op.c,
  215. p: op.p,
  216. t: op.t,
  217. },
  218. metadata,
  219. })
  220. )
  221. this._markAsDirty(comment, 'comment', 'added')
  222. }
  223. }
  224. applyInsertToComments(op) {
  225. for (const comment of this.comments) {
  226. if (op.p <= comment.op.p) {
  227. comment.op.p += op.i.length
  228. this._markAsDirty(comment, 'comment', 'moved')
  229. } else if (op.p < comment.op.p + comment.op.c.length) {
  230. const offset = op.p - comment.op.p
  231. comment.op.c =
  232. comment.op.c.slice(0, +(offset - 1) + 1 || undefined) +
  233. op.i +
  234. comment.op.c.slice(offset)
  235. this._markAsDirty(comment, 'comment', 'moved')
  236. }
  237. }
  238. }
  239. applyDeleteToComments(op) {
  240. const opStart = op.p
  241. const opLength = op.d.length
  242. const opEnd = op.p + opLength
  243. for (const comment of this.comments) {
  244. const commentStart = comment.op.p
  245. const commentEnd = comment.op.p + comment.op.c.length
  246. const commentLength = commentEnd - commentStart
  247. if (opEnd <= commentStart) {
  248. // delete is fully before comment
  249. comment.op.p -= opLength
  250. this._markAsDirty(comment, 'comment', 'moved')
  251. } else if (opStart >= commentEnd) {
  252. // delete is fully after comment, nothing to do
  253. } else {
  254. // delete and comment overlap
  255. let remainingAfter, remainingBefore
  256. if (opStart <= commentStart) {
  257. remainingBefore = ''
  258. } else {
  259. remainingBefore = comment.op.c.slice(0, opStart - commentStart)
  260. }
  261. if (opEnd >= commentEnd) {
  262. remainingAfter = ''
  263. } else {
  264. remainingAfter = comment.op.c.slice(opEnd - commentStart)
  265. }
  266. // Check deleted content matches delete op
  267. const deletedComment = comment.op.c.slice(
  268. remainingBefore.length,
  269. commentLength - remainingAfter.length
  270. )
  271. const offset = Math.max(0, commentStart - opStart)
  272. const deletedOpContent = op.d
  273. .slice(offset)
  274. .slice(0, deletedComment.length)
  275. if (deletedComment !== deletedOpContent) {
  276. throw new Error('deleted content does not match comment content')
  277. }
  278. comment.op.p = Math.min(commentStart, opStart)
  279. comment.op.c = remainingBefore + remainingAfter
  280. this._markAsDirty(comment, 'comment', 'moved')
  281. }
  282. }
  283. }
  284. applyInsertToChanges(op, metadata) {
  285. let change
  286. const opStart = op.p
  287. const opLength = op.i.length
  288. const opEnd = op.p + opLength
  289. const undoing = !!op.u
  290. let alreadyMerged = false
  291. let previousChange = null
  292. let trackedDeleteRejected = false
  293. const movedChanges = []
  294. const removeChanges = []
  295. const newChanges = []
  296. const trackedDeletesAtOpPosition = []
  297. for (let i = 0; i < this.changes.length; i++) {
  298. change = this.changes[i]
  299. const changeStart = change.op.p
  300. if (change.op.d != null) {
  301. // Shift any deletes after this along by the length of this insert
  302. if (opStart < changeStart) {
  303. change.op.p += opLength
  304. movedChanges.push(change)
  305. } else if (opStart === changeStart) {
  306. // Keep track of tracked deletes that are at the same position as the
  307. // insert. At the end of the loop, if we didn't find a tracked delete
  308. // to reject, we'll move these deletes after the insert.
  309. trackedDeletesAtOpPosition.push(change)
  310. if (trackedDeleteRejected && op.orderedRejections) {
  311. // We rejected a tracked delete. Move the remaining tracked deletes after the insert
  312. change.op.p += opLength
  313. movedChanges.push(change)
  314. } else if (
  315. undoing &&
  316. change.op.d.length >= op.i.length &&
  317. change.op.d.slice(0, op.i.length) === op.i
  318. ) {
  319. // If we are undoing, then we want to reject any existing tracked delete if we can.
  320. // Check if the insert matches the start of the delete, and just remove it from the delete instead if so.
  321. change.op.d = change.op.d.slice(op.i.length)
  322. change.op.p += op.i.length
  323. if (change.op.d === '') {
  324. removeChanges.push(change)
  325. } else {
  326. movedChanges.push(change)
  327. }
  328. alreadyMerged = true
  329. trackedDeleteRejected = true
  330. }
  331. }
  332. } else if (change.op.i != null) {
  333. let offset
  334. const changeEnd = changeStart + change.op.i.length
  335. const isChangeOverlapping =
  336. opStart >= changeStart && opStart <= changeEnd
  337. // Only merge inserts if they are from the same user
  338. const isSameUser = metadata.user_id === change.metadata.user_id
  339. // If we are undoing, then our changes will be removed from any delete ops just after. In that case, if there is also
  340. // an insert op just before, then we shouldn't append it to this insert, but instead only cancel the following delete.
  341. // E.g.
  342. // foo|<--- about to insert 'b' here
  343. // inserted 'foo' --^ ^-- deleted 'bar'
  344. // should become just 'foo' not 'foob' (with the delete marker becoming just 'ar'), .
  345. const nextChange = this.changes[i + 1]
  346. const isOpAdjacentToNextDelete =
  347. nextChange != null &&
  348. nextChange.op.d != null &&
  349. op.p === changeEnd &&
  350. nextChange.op.p === op.p
  351. const willOpCancelNextDelete =
  352. undoing &&
  353. isOpAdjacentToNextDelete &&
  354. nextChange.op.d.slice(0, op.i.length) === op.i
  355. // If there is a delete at the start of the insert, and we're inserting
  356. // at the start, we SHOULDN'T merge since the delete acts as a partition.
  357. // The previous op will be the delete, but it's already been shifted by this insert
  358. //
  359. // I.e.
  360. // Originally: |-- existing insert --|
  361. // | <- existing delete at same offset
  362. //
  363. // Now: |-- existing insert --| <- not shifted yet
  364. // |-- this insert --|| <- existing delete shifted along to end of this op
  365. //
  366. // After: |-- existing insert --|
  367. // |-- this insert --|| <- existing delete
  368. //
  369. // Without the delete, the inserts would be merged.
  370. const isInsertBlockedByDelete =
  371. previousChange != null &&
  372. previousChange.op.d != null &&
  373. previousChange.op.p === opEnd
  374. // If the insert is overlapping another insert, either at the beginning in the middle or touching the end,
  375. // then we merge them into one.
  376. if (
  377. this.track_changes &&
  378. isChangeOverlapping &&
  379. !isInsertBlockedByDelete &&
  380. !alreadyMerged &&
  381. !willOpCancelNextDelete &&
  382. isSameUser
  383. ) {
  384. offset = opStart - changeStart
  385. change.op.i =
  386. change.op.i.slice(0, offset) + op.i + change.op.i.slice(offset)
  387. change.metadata.ts = metadata.ts
  388. alreadyMerged = true
  389. movedChanges.push(change)
  390. } else if (opStart <= changeStart) {
  391. // If we're fully before the other insert we can just shift the other insert by our length.
  392. // If they are touching, and should have been merged, they will have been above.
  393. // If not merged above, then it must be blocked by a delete, and will be after this insert, so we shift it along as well
  394. change.op.p += opLength
  395. movedChanges.push(change)
  396. } else if (
  397. (!isSameUser || !this.track_changes) &&
  398. changeStart < opStart &&
  399. opStart < changeEnd
  400. ) {
  401. // This user is inserting inside a change by another user, so we need to split the
  402. // other user's change into one before and after this one.
  403. offset = opStart - changeStart
  404. const beforeContent = change.op.i.slice(0, offset)
  405. const afterContent = change.op.i.slice(offset)
  406. // The existing change can become the 'before' change
  407. change.op.i = beforeContent
  408. movedChanges.push(change)
  409. // Create a new op afterwards
  410. const afterChange = {
  411. op: {
  412. i: afterContent,
  413. p: changeStart + offset + opLength,
  414. },
  415. metadata: {},
  416. }
  417. for (const key in change.metadata) {
  418. const value = change.metadata[key]
  419. afterChange.metadata[key] = value
  420. }
  421. newChanges.push(afterChange)
  422. }
  423. }
  424. previousChange = change
  425. }
  426. if (!trackedDeleteRejected || !op.orderedRejections) {
  427. // We didn't reject any tracked delete. Move all existing tracked deletes
  428. // at the insert position after the insert
  429. for (const change of trackedDeletesAtOpPosition) {
  430. change.op.p += opLength
  431. movedChanges.push(change)
  432. }
  433. }
  434. if (this.track_changes && !alreadyMerged) {
  435. this._addOp(op, metadata)
  436. }
  437. for ({ op, metadata } of newChanges) {
  438. this._addOp(op, metadata)
  439. }
  440. for (change of removeChanges) {
  441. this._removeChange(change)
  442. }
  443. for (change of movedChanges) {
  444. this._markAsDirty(change, 'change', 'moved')
  445. }
  446. }
  447. applyDeleteToChanges(op, metadata) {
  448. const opStart = op.p
  449. const opLength = op.d.length
  450. const opEnd = op.p + opLength
  451. const removeChanges = []
  452. let movedChanges = []
  453. // We might end up modifying our delete op if it merges with existing deletes, or cancels out
  454. // with an existing insert. Since we might do multiple modifications, we record them and do
  455. // all the modifications after looping through the existing changes, so as not to mess up the
  456. // offset indexes as we go.
  457. const opModifications = []
  458. for (const change of this.changes) {
  459. let changeStart
  460. if (change.op.i != null) {
  461. changeStart = change.op.p
  462. const changeEnd = changeStart + change.op.i.length
  463. if (opEnd <= changeStart) {
  464. // Shift ops after us back by our length
  465. change.op.p -= opLength
  466. movedChanges.push(change)
  467. } else if (opStart >= changeEnd) {
  468. // Delete is after insert, nothing to do
  469. } else {
  470. // When the new delete overlaps an insert, we should remove the part of the insert that
  471. // is now deleted, and also remove the part of the new delete that overlapped. I.e.
  472. // the two cancel out where they overlap.
  473. let deleteRemainingAfter,
  474. deleteRemainingBefore,
  475. insertRemainingAfter,
  476. insertRemainingBefore
  477. if (opStart >= changeStart) {
  478. // |-- existing insert --|
  479. // insertRemainingBefore -> |.....||-- new delete --|
  480. deleteRemainingBefore = ''
  481. insertRemainingBefore = change.op.i.slice(0, opStart - changeStart)
  482. } else {
  483. // deleteRemainingBefore -> |.....||-- existing insert --|
  484. // |-- new delete --|
  485. deleteRemainingBefore = op.d.slice(0, changeStart - opStart)
  486. insertRemainingBefore = ''
  487. }
  488. if (opEnd <= changeEnd) {
  489. // |-- existing insert --|
  490. // |-- new delete --||.....| <- insertRemainingAfter
  491. deleteRemainingAfter = ''
  492. insertRemainingAfter = change.op.i.slice(opEnd - changeStart)
  493. } else {
  494. // |-- existing insert --||.....| <- deleteRemainingAfter
  495. // |-- new delete --|
  496. deleteRemainingAfter = op.d.slice(changeEnd - opStart)
  497. insertRemainingAfter = ''
  498. }
  499. const insertRemaining = insertRemainingBefore + insertRemainingAfter
  500. if (insertRemaining.length > 0) {
  501. change.op.i = insertRemaining
  502. change.op.p = Math.min(changeStart, opStart)
  503. movedChanges.push(change)
  504. } else {
  505. removeChanges.push(change)
  506. }
  507. // We know what we want to preserve of our delete op before (deleteRemainingBefore) and what we want to preserve
  508. // afterwards (deleteRemainingBefore). Now we need to turn that into a modification which deletes the
  509. // chunk in the middle not covered by these.
  510. const deleteRemovedLength =
  511. op.d.length -
  512. deleteRemainingBefore.length -
  513. deleteRemainingAfter.length
  514. const deleteRemovedStart = deleteRemainingBefore.length
  515. const modification = {
  516. d: op.d.slice(
  517. deleteRemovedStart,
  518. deleteRemovedStart + deleteRemovedLength
  519. ),
  520. p: deleteRemovedStart,
  521. }
  522. if (modification.d.length > 0) {
  523. opModifications.push(modification)
  524. }
  525. }
  526. } else if (change.op.d != null) {
  527. changeStart = change.op.p
  528. if (
  529. opEnd < changeStart ||
  530. (!this.track_changes && opEnd === changeStart)
  531. ) {
  532. // Shift ops after us back by our length.
  533. // If we're tracking changes, it must be strictly before, since we'll merge
  534. // below if they are touching. Otherwise, touching is fine.
  535. change.op.p -= opLength
  536. movedChanges.push(change)
  537. } else if (opStart <= changeStart && changeStart <= opEnd) {
  538. if (this.track_changes) {
  539. // If we overlap a delete, add it in our content, and delete the existing change.
  540. // It's easier to do it this way, rather than modifying the existing delete in case
  541. // we overlap many deletes and we'd need to track that. We have a workaround to
  542. // update the delete in place if possible below.
  543. const offset = changeStart - opStart
  544. opModifications.push({ i: change.op.d, p: offset })
  545. removeChanges.push(change)
  546. } else {
  547. change.op.p = opStart
  548. movedChanges.push(change)
  549. }
  550. }
  551. }
  552. }
  553. // Copy rather than modify because we still need to apply it to comments
  554. op = {
  555. p: op.p,
  556. d: this._applyOpModifications(op.d, opModifications),
  557. }
  558. for (const change of removeChanges) {
  559. // This is a bit of hack to avoid removing one delete and replacing it with another.
  560. // If we don't do this, it causes the UI to flicker
  561. if (
  562. op.d.length > 0 &&
  563. change.op.d != null &&
  564. op.p <= change.op.p &&
  565. change.op.p <= op.p + op.d.length
  566. ) {
  567. change.op.p = op.p
  568. change.op.d = op.d
  569. change.metadata = metadata
  570. movedChanges.push(change)
  571. op.d = '' // stop it being added
  572. } else {
  573. this._removeChange(change)
  574. }
  575. }
  576. if (this.track_changes && op.d.length > 0) {
  577. this._addOp(op, metadata)
  578. } else {
  579. // It's possible that we deleted an insert between two other inserts. I.e.
  580. // If we delete 'user_2 insert' in:
  581. // |-- user_1 insert --||-- user_2 insert --||-- user_1 insert --|
  582. // it becomes:
  583. // |-- user_1 insert --||-- user_1 insert --|
  584. // We need to merge these together again
  585. const results = this._scanAndMergeAdjacentUpdates()
  586. movedChanges = movedChanges.concat(results.movedChanges)
  587. for (const change of results.removeChanges) {
  588. this._removeChange(change)
  589. movedChanges = movedChanges.filter(c => c !== change)
  590. }
  591. }
  592. for (const change of movedChanges) {
  593. this._markAsDirty(change, 'change', 'moved')
  594. }
  595. }
  596. _addOp(op, metadata) {
  597. // Don't take a reference to the existing op since we'll modify this in place with future changes
  598. op = this._clone(op)
  599. // TODO: Remove this when the orderedRejections transition is over
  600. delete op.orderedRejections
  601. const change = {
  602. id: this.newId(),
  603. op,
  604. metadata: this._clone(metadata),
  605. }
  606. this.changes.push(change)
  607. // Keep ops in order of offset, with deletes before inserts
  608. this.changes.sort(function (c1, c2) {
  609. const result = c1.op.p - c2.op.p
  610. if (result !== 0) {
  611. return result
  612. } else if (c1.op.i != null && c2.op.d != null) {
  613. return 1
  614. } else if (c1.op.d != null && c2.op.i != null) {
  615. return -1
  616. } else {
  617. return 0
  618. }
  619. })
  620. this._markAsDirty(change, 'change', 'added')
  621. }
  622. _removeChange(change) {
  623. this.changes = this.changes.filter(c => c.id !== change.id)
  624. this._markAsDirty(change, 'change', 'removed')
  625. }
  626. _applyOpModifications(content, opModifications) {
  627. // Put in descending position order, with deleting first if at the same offset
  628. // (Inserting first would modify the content that the delete will delete)
  629. opModifications.sort(function (a, b) {
  630. const result = b.p - a.p
  631. if (result !== 0) {
  632. return result
  633. } else if (a.i != null && b.d != null) {
  634. return 1
  635. } else if (a.d != null && b.i != null) {
  636. return -1
  637. } else {
  638. return 0
  639. }
  640. })
  641. for (const modification of opModifications) {
  642. if (modification.i != null) {
  643. content =
  644. content.slice(0, modification.p) +
  645. modification.i +
  646. content.slice(modification.p)
  647. } else if (modification.d != null) {
  648. if (
  649. content.slice(
  650. modification.p,
  651. modification.p + modification.d.length
  652. ) !== modification.d
  653. ) {
  654. throw new Error('deletion does not match text in document')
  655. }
  656. content =
  657. content.slice(0, modification.p) +
  658. content.slice(modification.p + modification.d.length)
  659. }
  660. }
  661. return content
  662. }
  663. _scanAndMergeAdjacentUpdates() {
  664. // This should only need calling when deleting an update between two
  665. // other updates. There's no other way to get two adjacent updates from the
  666. // same user, since they would be merged on insert.
  667. let previousChange = null
  668. const removeChanges = []
  669. const movedChanges = []
  670. for (const change of this.changes) {
  671. if (previousChange?.op.i != null && change.op.i != null) {
  672. const previousChangeEnd =
  673. previousChange.op.p + previousChange.op.i.length
  674. const previousChangeUserId = previousChange.metadata.user_id
  675. const changeStart = change.op.p
  676. const changeUserId = change.metadata.user_id
  677. if (
  678. previousChangeEnd === changeStart &&
  679. previousChangeUserId === changeUserId
  680. ) {
  681. removeChanges.push(change)
  682. previousChange.op.i += change.op.i
  683. movedChanges.push(previousChange)
  684. }
  685. } else if (
  686. previousChange?.op.d != null &&
  687. change.op.d != null &&
  688. previousChange?.op.p === change.op.p
  689. ) {
  690. // Merge adjacent deletes
  691. previousChange.op.d += change.op.d
  692. removeChanges.push(change)
  693. movedChanges.push(previousChange)
  694. } else {
  695. // Only update to the current change if we haven't removed it.
  696. previousChange = change
  697. }
  698. }
  699. return { movedChanges, removeChanges }
  700. }
  701. resetDirtyState() {
  702. this._dirtyState = {
  703. comment: {
  704. moved: {},
  705. removed: {},
  706. added: {},
  707. },
  708. change: {
  709. moved: {},
  710. removed: {},
  711. added: {},
  712. },
  713. }
  714. }
  715. getDirtyState() {
  716. return this._dirtyState
  717. }
  718. getTrackedDeletesLength() {
  719. let length = 0
  720. for (const change of this.changes) {
  721. if (change.op.d != null) {
  722. length += change.op.d.length
  723. }
  724. }
  725. return length
  726. }
  727. _markAsDirty(object, type, action) {
  728. this._dirtyState[type][action][object.id] = object
  729. }
  730. _clone(object) {
  731. const clone = {}
  732. for (const k in object) {
  733. const v = object[k]
  734. clone[k] = v
  735. }
  736. return clone
  737. }
  738. }
  739. module.exports = RangesTracker