index.cjs 26 KB

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