index.cjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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(changeIds) {
  133. const changesResponse = []
  134. const idsMap = {}
  135. for (const changeId of changeIds) {
  136. idsMap[changeId] = true
  137. }
  138. for (const change of this.changes) {
  139. if (idsMap[change.id]) {
  140. delete idsMap[change.id]
  141. changesResponse.push(change)
  142. }
  143. }
  144. return changesResponse
  145. }
  146. removeChangeId(changeId) {
  147. const change = this.getChange(changeId)
  148. if (change == null) {
  149. return
  150. }
  151. this._removeChange(change)
  152. }
  153. removeChangeIds(changeToRemoveIds) {
  154. if (changeToRemoveIds == null || changeToRemoveIds.length === 0) {
  155. return
  156. }
  157. const removeChangeId = {}
  158. for (const changeId of changeToRemoveIds) {
  159. removeChangeId[changeId] = true
  160. }
  161. const remainingChanges = []
  162. for (const change of this.changes) {
  163. if (removeChangeId[change.id]) {
  164. delete removeChangeId[change.id]
  165. this._markAsDirty(change, 'change', 'removed')
  166. } else {
  167. remainingChanges.push(change)
  168. }
  169. }
  170. this.changes = remainingChanges
  171. }
  172. validate(text) {
  173. let content
  174. for (const change of this.changes) {
  175. if (change.op.i != null) {
  176. content = text.slice(change.op.p, change.op.p + change.op.i.length)
  177. if (content !== change.op.i) {
  178. throw new Error('insertion does not match text in document')
  179. }
  180. }
  181. }
  182. for (const comment of this.comments) {
  183. content = text.slice(comment.op.p, comment.op.p + comment.op.c.length)
  184. if (content !== comment.op.c) {
  185. throw new Error('comment does not match text in document')
  186. }
  187. }
  188. }
  189. applyOp(op, metadata) {
  190. if (metadata == null) {
  191. metadata = {}
  192. }
  193. if (metadata.ts == null) {
  194. metadata.ts = new Date()
  195. }
  196. // Apply an op that has been applied to the document to our changes to keep them up to date
  197. if (op.i != null) {
  198. this.applyInsertToChanges(op, metadata)
  199. this.applyInsertToComments(op)
  200. } else if (op.d != null) {
  201. this.applyDeleteToChanges(op, metadata)
  202. this.applyDeleteToComments(op)
  203. } else if (op.c != null) {
  204. this.addComment(op, metadata)
  205. } else {
  206. throw new Error('unknown op type')
  207. }
  208. }
  209. applyOps(ops, metadata) {
  210. if (metadata == null) {
  211. metadata = {}
  212. }
  213. for (const op of ops) {
  214. this.applyOp(op, metadata)
  215. }
  216. }
  217. addComment(op, metadata) {
  218. const existing = this.getComment(op.t)
  219. if (existing != null) {
  220. this.moveCommentId(op.t, op.p, op.c)
  221. } else {
  222. let comment
  223. this.comments.push(
  224. (comment = {
  225. id: op.t || this.newId(),
  226. op: {
  227. // Copy because we'll modify in place
  228. c: op.c,
  229. p: op.p,
  230. t: op.t,
  231. },
  232. metadata,
  233. })
  234. )
  235. this._markAsDirty(comment, 'comment', 'added')
  236. }
  237. }
  238. applyInsertToComments(op) {
  239. for (const comment of this.comments) {
  240. if (op.p <= comment.op.p) {
  241. comment.op.p += op.i.length
  242. this._markAsDirty(comment, 'comment', 'moved')
  243. } else if (op.p < comment.op.p + comment.op.c.length) {
  244. const offset = op.p - comment.op.p
  245. comment.op.c =
  246. comment.op.c.slice(0, +(offset - 1) + 1 || undefined) +
  247. op.i +
  248. comment.op.c.slice(offset)
  249. this._markAsDirty(comment, 'comment', 'moved')
  250. }
  251. }
  252. }
  253. applyDeleteToComments(op) {
  254. const opStart = op.p
  255. const opLength = op.d.length
  256. const opEnd = op.p + opLength
  257. for (const comment of this.comments) {
  258. const commentStart = comment.op.p
  259. const commentEnd = comment.op.p + comment.op.c.length
  260. const commentLength = commentEnd - commentStart
  261. if (opEnd <= commentStart) {
  262. // delete is fully before comment
  263. comment.op.p -= opLength
  264. this._markAsDirty(comment, 'comment', 'moved')
  265. } else if (opStart >= commentEnd) {
  266. // delete is fully after comment, nothing to do
  267. } else {
  268. // delete and comment overlap
  269. let remainingAfter, remainingBefore
  270. if (opStart <= commentStart) {
  271. remainingBefore = ''
  272. } else {
  273. remainingBefore = comment.op.c.slice(0, opStart - commentStart)
  274. }
  275. if (opEnd >= commentEnd) {
  276. remainingAfter = ''
  277. } else {
  278. remainingAfter = comment.op.c.slice(opEnd - commentStart)
  279. }
  280. // Check deleted content matches delete op
  281. const deletedComment = comment.op.c.slice(
  282. remainingBefore.length,
  283. commentLength - remainingAfter.length
  284. )
  285. const offset = Math.max(0, commentStart - opStart)
  286. const deletedOpContent = op.d
  287. .slice(offset)
  288. .slice(0, deletedComment.length)
  289. if (deletedComment !== deletedOpContent) {
  290. throw new Error('deleted content does not match comment content')
  291. }
  292. comment.op.p = Math.min(commentStart, opStart)
  293. comment.op.c = remainingBefore + remainingAfter
  294. this._markAsDirty(comment, 'comment', 'moved')
  295. }
  296. }
  297. }
  298. applyInsertToChanges(op, metadata) {
  299. let change
  300. const opStart = op.p
  301. const opLength = op.i.length
  302. const opEnd = op.p + opLength
  303. const undoing = !!op.u
  304. let alreadyMerged = false
  305. let previousChange = null
  306. const movedChanges = []
  307. const removeChanges = []
  308. const newChanges = []
  309. for (let i = 0; i < this.changes.length; i++) {
  310. change = this.changes[i]
  311. const changeStart = change.op.p
  312. if (change.op.d != null) {
  313. // Shift any deletes after this along by the length of this insert
  314. if (opStart < changeStart) {
  315. change.op.p += opLength
  316. movedChanges.push(change)
  317. } else if (opStart === changeStart) {
  318. // If we are undoing, then we want to cancel any existing delete ranges if we can.
  319. // Check if the insert matches the start of the delete, and just remove it from the delete instead if so.
  320. if (
  321. undoing &&
  322. change.op.d.length >= op.i.length &&
  323. change.op.d.slice(0, op.i.length) === op.i
  324. ) {
  325. change.op.d = change.op.d.slice(op.i.length)
  326. change.op.p += op.i.length
  327. if (change.op.d === '') {
  328. removeChanges.push(change)
  329. } else {
  330. movedChanges.push(change)
  331. }
  332. alreadyMerged = true
  333. } else {
  334. change.op.p += opLength
  335. movedChanges.push(change)
  336. }
  337. }
  338. } else if (change.op.i != null) {
  339. let offset
  340. const changeEnd = changeStart + change.op.i.length
  341. const isChangeOverlapping =
  342. opStart >= changeStart && opStart <= changeEnd
  343. // Only merge inserts if they are from the same user
  344. const isSameUser = metadata.user_id === change.metadata.user_id
  345. // If we are undoing, then our changes will be removed from any delete ops just after. In that case, if there is also
  346. // an insert op just before, then we shouldn't append it to this insert, but instead only cancel the following delete.
  347. // E.g.
  348. // foo|<--- about to insert 'b' here
  349. // inserted 'foo' --^ ^-- deleted 'bar'
  350. // should become just 'foo' not 'foob' (with the delete marker becoming just 'ar'), .
  351. const nextChange = this.changes[i + 1]
  352. const isOpAdjacentToNextDelete =
  353. nextChange != null &&
  354. nextChange.op.d != null &&
  355. op.p === changeEnd &&
  356. nextChange.op.p === op.p
  357. const willOpCancelNextDelete =
  358. undoing &&
  359. isOpAdjacentToNextDelete &&
  360. nextChange.op.d.slice(0, op.i.length) === op.i
  361. // If there is a delete at the start of the insert, and we're inserting
  362. // at the start, we SHOULDN'T merge since the delete acts as a partition.
  363. // The previous op will be the delete, but it's already been shifted by this insert
  364. //
  365. // I.e.
  366. // Originally: |-- existing insert --|
  367. // | <- existing delete at same offset
  368. //
  369. // Now: |-- existing insert --| <- not shifted yet
  370. // |-- this insert --|| <- existing delete shifted along to end of this op
  371. //
  372. // After: |-- existing insert --|
  373. // |-- this insert --|| <- existing delete
  374. //
  375. // Without the delete, the inserts would be merged.
  376. const isInsertBlockedByDelete =
  377. previousChange != null &&
  378. previousChange.op.d != null &&
  379. previousChange.op.p === opEnd
  380. // If the insert is overlapping another insert, either at the beginning in the middle or touching the end,
  381. // then we merge them into one.
  382. if (
  383. this.track_changes &&
  384. isChangeOverlapping &&
  385. !isInsertBlockedByDelete &&
  386. !alreadyMerged &&
  387. !willOpCancelNextDelete &&
  388. isSameUser
  389. ) {
  390. offset = opStart - changeStart
  391. change.op.i =
  392. change.op.i.slice(0, offset) + op.i + change.op.i.slice(offset)
  393. change.metadata.ts = metadata.ts
  394. alreadyMerged = true
  395. movedChanges.push(change)
  396. } else if (opStart <= changeStart) {
  397. // If we're fully before the other insert we can just shift the other insert by our length.
  398. // If they are touching, and should have been merged, they will have been above.
  399. // 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
  400. change.op.p += opLength
  401. movedChanges.push(change)
  402. } else if (
  403. (!isSameUser || !this.track_changes) &&
  404. changeStart < opStart &&
  405. opStart < changeEnd
  406. ) {
  407. // This user is inserting inside a change by another user, so we need to split the
  408. // other user's change into one before and after this one.
  409. offset = opStart - changeStart
  410. const beforeContent = change.op.i.slice(0, offset)
  411. const afterContent = change.op.i.slice(offset)
  412. // The existing change can become the 'before' change
  413. change.op.i = beforeContent
  414. movedChanges.push(change)
  415. // Create a new op afterwards
  416. const afterChange = {
  417. op: {
  418. i: afterContent,
  419. p: changeStart + offset + opLength,
  420. },
  421. metadata: {},
  422. }
  423. for (const key in change.metadata) {
  424. const value = change.metadata[key]
  425. afterChange.metadata[key] = value
  426. }
  427. newChanges.push(afterChange)
  428. }
  429. }
  430. previousChange = change
  431. }
  432. if (this.track_changes && !alreadyMerged) {
  433. this._addOp(op, metadata)
  434. }
  435. for ({ op, metadata } of newChanges) {
  436. this._addOp(op, metadata)
  437. }
  438. for (change of removeChanges) {
  439. this._removeChange(change)
  440. }
  441. for (change of movedChanges) {
  442. this._markAsDirty(change, 'change', 'moved')
  443. }
  444. }
  445. applyDeleteToChanges(op, metadata) {
  446. const opStart = op.p
  447. const opLength = op.d.length
  448. const opEnd = op.p + opLength
  449. const removeChanges = []
  450. let movedChanges = []
  451. // We might end up modifying our delete op if it merges with existing deletes, or cancels out
  452. // with an existing insert. Since we might do multiple modifications, we record them and do
  453. // all the modifications after looping through the existing changes, so as not to mess up the
  454. // offset indexes as we go.
  455. const opModifications = []
  456. for (const change of this.changes) {
  457. let changeStart
  458. if (change.op.i != null) {
  459. changeStart = change.op.p
  460. const changeEnd = changeStart + change.op.i.length
  461. if (opEnd <= changeStart) {
  462. // Shift ops after us back by our length
  463. change.op.p -= opLength
  464. movedChanges.push(change)
  465. } else if (opStart >= changeEnd) {
  466. // Delete is after insert, nothing to do
  467. } else {
  468. // When the new delete overlaps an insert, we should remove the part of the insert that
  469. // is now deleted, and also remove the part of the new delete that overlapped. I.e.
  470. // the two cancel out where they overlap.
  471. let deleteRemainingAfter,
  472. deleteRemainingBefore,
  473. insertRemainingAfter,
  474. insertRemainingBefore
  475. if (opStart >= changeStart) {
  476. // |-- existing insert --|
  477. // insertRemainingBefore -> |.....||-- new delete --|
  478. deleteRemainingBefore = ''
  479. insertRemainingBefore = change.op.i.slice(0, opStart - changeStart)
  480. } else {
  481. // deleteRemainingBefore -> |.....||-- existing insert --|
  482. // |-- new delete --|
  483. deleteRemainingBefore = op.d.slice(0, changeStart - opStart)
  484. insertRemainingBefore = ''
  485. }
  486. if (opEnd <= changeEnd) {
  487. // |-- existing insert --|
  488. // |-- new delete --||.....| <- insertRemainingAfter
  489. deleteRemainingAfter = ''
  490. insertRemainingAfter = change.op.i.slice(opEnd - changeStart)
  491. } else {
  492. // |-- existing insert --||.....| <- deleteRemainingAfter
  493. // |-- new delete --|
  494. deleteRemainingAfter = op.d.slice(changeEnd - opStart)
  495. insertRemainingAfter = ''
  496. }
  497. const insertRemaining = insertRemainingBefore + insertRemainingAfter
  498. if (insertRemaining.length > 0) {
  499. change.op.i = insertRemaining
  500. change.op.p = Math.min(changeStart, opStart)
  501. movedChanges.push(change)
  502. } else {
  503. removeChanges.push(change)
  504. }
  505. // We know what we want to preserve of our delete op before (deleteRemainingBefore) and what we want to preserve
  506. // afterwards (deleteRemainingBefore). Now we need to turn that into a modification which deletes the
  507. // chunk in the middle not covered by these.
  508. const deleteRemovedLength =
  509. op.d.length -
  510. deleteRemainingBefore.length -
  511. deleteRemainingAfter.length
  512. const deleteRemovedStart = deleteRemainingBefore.length
  513. const modification = {
  514. d: op.d.slice(
  515. deleteRemovedStart,
  516. deleteRemovedStart + deleteRemovedLength
  517. ),
  518. p: deleteRemovedStart,
  519. }
  520. if (modification.d.length > 0) {
  521. opModifications.push(modification)
  522. }
  523. }
  524. } else if (change.op.d != null) {
  525. changeStart = change.op.p
  526. if (
  527. opEnd < changeStart ||
  528. (!this.track_changes && opEnd === changeStart)
  529. ) {
  530. // Shift ops after us back by our length.
  531. // If we're tracking changes, it must be strictly before, since we'll merge
  532. // below if they are touching. Otherwise, touching is fine.
  533. change.op.p -= opLength
  534. movedChanges.push(change)
  535. } else if (opStart <= changeStart && changeStart <= opEnd) {
  536. if (this.track_changes) {
  537. // If we overlap a delete, add it in our content, and delete the existing change.
  538. // It's easier to do it this way, rather than modifying the existing delete in case
  539. // we overlap many deletes and we'd need to track that. We have a workaround to
  540. // update the delete in place if possible below.
  541. const offset = changeStart - opStart
  542. opModifications.push({ i: change.op.d, p: offset })
  543. removeChanges.push(change)
  544. } else {
  545. change.op.p = opStart
  546. movedChanges.push(change)
  547. }
  548. }
  549. }
  550. }
  551. // Copy rather than modify because we still need to apply it to comments
  552. op = {
  553. p: op.p,
  554. d: this._applyOpModifications(op.d, opModifications),
  555. }
  556. for (const change of removeChanges) {
  557. // This is a bit of hack to avoid removing one delete and replacing it with another.
  558. // If we don't do this, it causes the UI to flicker
  559. if (
  560. op.d.length > 0 &&
  561. change.op.d != null &&
  562. op.p <= change.op.p &&
  563. change.op.p <= op.p + op.d.length
  564. ) {
  565. change.op.p = op.p
  566. change.op.d = op.d
  567. change.metadata = metadata
  568. movedChanges.push(change)
  569. op.d = '' // stop it being added
  570. } else {
  571. this._removeChange(change)
  572. }
  573. }
  574. if (this.track_changes && op.d.length > 0) {
  575. this._addOp(op, metadata)
  576. } else {
  577. // It's possible that we deleted an insert between two other inserts. I.e.
  578. // If we delete 'user_2 insert' in:
  579. // |-- user_1 insert --||-- user_2 insert --||-- user_1 insert --|
  580. // it becomes:
  581. // |-- user_1 insert --||-- user_1 insert --|
  582. // We need to merge these together again
  583. const results = this._scanAndMergeAdjacentUpdates()
  584. movedChanges = movedChanges.concat(results.movedChanges)
  585. for (const change of results.removeChanges) {
  586. this._removeChange(change)
  587. movedChanges = movedChanges.filter(c => c !== change)
  588. }
  589. }
  590. for (const change of movedChanges) {
  591. this._markAsDirty(change, 'change', 'moved')
  592. }
  593. }
  594. _addOp(op, metadata) {
  595. const change = {
  596. id: this.newId(),
  597. op: this._clone(op), // Don't take a reference to the existing op since we'll modify this in place with future changes
  598. metadata: this._clone(metadata),
  599. }
  600. this.changes.push(change)
  601. // Keep ops in order of offset, with deletes before inserts
  602. this.changes.sort(function (c1, c2) {
  603. const result = c1.op.p - c2.op.p
  604. if (result !== 0) {
  605. return result
  606. } else if (c1.op.i != null && c2.op.d != null) {
  607. return 1
  608. } else if (c1.op.d != null && c2.op.i != null) {
  609. return -1
  610. } else {
  611. return 0
  612. }
  613. })
  614. this._markAsDirty(change, 'change', 'added')
  615. }
  616. _removeChange(change) {
  617. this.changes = this.changes.filter(c => c.id !== change.id)
  618. this._markAsDirty(change, 'change', 'removed')
  619. }
  620. _applyOpModifications(content, opModifications) {
  621. // Put in descending position order, with deleting first if at the same offset
  622. // (Inserting first would modify the content that the delete will delete)
  623. opModifications.sort(function (a, b) {
  624. const result = b.p - a.p
  625. if (result !== 0) {
  626. return result
  627. } else if (a.i != null && b.d != null) {
  628. return 1
  629. } else if (a.d != null && b.i != null) {
  630. return -1
  631. } else {
  632. return 0
  633. }
  634. })
  635. for (const modification of opModifications) {
  636. if (modification.i != null) {
  637. content =
  638. content.slice(0, modification.p) +
  639. modification.i +
  640. content.slice(modification.p)
  641. } else if (modification.d != null) {
  642. if (
  643. content.slice(
  644. modification.p,
  645. modification.p + modification.d.length
  646. ) !== modification.d
  647. ) {
  648. throw new Error('deletion does not match text in document')
  649. }
  650. content =
  651. content.slice(0, modification.p) +
  652. content.slice(modification.p + modification.d.length)
  653. }
  654. }
  655. return content
  656. }
  657. _scanAndMergeAdjacentUpdates() {
  658. // This should only need calling when deleting an update between two
  659. // other updates. There's no other way to get two adjacent updates from the
  660. // same user, since they would be merged on insert.
  661. let previousChange = null
  662. const removeChanges = []
  663. const movedChanges = []
  664. for (const change of this.changes) {
  665. if (previousChange?.op.i != null && change.op.i != null) {
  666. const previousChangeEnd =
  667. previousChange.op.p + previousChange.op.i.length
  668. const previousChangeUserId = previousChange.metadata.user_id
  669. const changeStart = change.op.p
  670. const changeUserId = change.metadata.user_id
  671. if (
  672. previousChangeEnd === changeStart &&
  673. previousChangeUserId === changeUserId
  674. ) {
  675. removeChanges.push(change)
  676. previousChange.op.i += change.op.i
  677. movedChanges.push(previousChange)
  678. }
  679. } else if (
  680. previousChange?.op.d != null &&
  681. change.op.d != null &&
  682. previousChange?.op.p === change.op.p
  683. ) {
  684. // Merge adjacent deletes
  685. previousChange.op.d += change.op.d
  686. removeChanges.push(change)
  687. movedChanges.push(previousChange)
  688. } else {
  689. // Only update to the current change if we haven't removed it.
  690. previousChange = change
  691. }
  692. }
  693. return { movedChanges, removeChanges }
  694. }
  695. resetDirtyState() {
  696. this._dirtyState = {
  697. comment: {
  698. moved: {},
  699. removed: {},
  700. added: {},
  701. },
  702. change: {
  703. moved: {},
  704. removed: {},
  705. added: {},
  706. },
  707. }
  708. }
  709. getDirtyState() {
  710. return this._dirtyState
  711. }
  712. _markAsDirty(object, type, action) {
  713. this._dirtyState[type][action][object.id] = object
  714. }
  715. _clone(object) {
  716. const clone = {}
  717. for (const k in object) {
  718. const v = object[k]
  719. clone[k] = v
  720. }
  721. return clone
  722. }
  723. }
  724. module.exports = RangesTracker