RangesTracker.coffee 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. load = (EventEmitter) ->
  2. class RangesTracker extends EventEmitter
  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. constructor: (@changes = [], @comments = []) ->
  38. @setIdSeed(RangesTracker.generateIdSeed())
  39. getIdSeed: () ->
  40. return @id_seed
  41. setIdSeed: (seed) ->
  42. @id_seed = seed
  43. @id_increment = 0
  44. @generateIdSeed: () ->
  45. # Generate a the first 18 characters of Mongo ObjectId, leaving 6 for the increment part
  46. # Reference: https://github.com/dreampulse/ObjectId.js/blob/master/src/main/javascript/Objectid.js
  47. pid = Math.floor(Math.random() * (32767)).toString(16)
  48. machine = Math.floor(Math.random() * (16777216)).toString(16)
  49. timestamp = Math.floor(new Date().valueOf() / 1000).toString(16)
  50. return '00000000'.substr(0, 8 - timestamp.length) + timestamp +
  51. '000000'.substr(0, 6 - machine.length) + machine +
  52. '0000'.substr(0, 4 - pid.length) + pid
  53. @generateId: () ->
  54. @generateIdSeed() + "000001"
  55. newId: () ->
  56. @id_increment++
  57. increment = @id_increment.toString(16)
  58. id = @id_seed + '000000'.substr(0, 6 - increment.length) + increment;
  59. return id
  60. getComment: (comment_id) ->
  61. comment = null
  62. for c in @comments
  63. if c.id == comment_id
  64. comment = c
  65. break
  66. return comment
  67. removeCommentId: (comment_id) ->
  68. comment = @getComment(comment_id)
  69. return if !comment?
  70. @comments = @comments.filter (c) -> c.id != comment_id
  71. @emit "comment:removed", comment
  72. getChange: (change_id) ->
  73. change = null
  74. for c in @changes
  75. if c.id == change_id
  76. change = c
  77. break
  78. return change
  79. removeChangeId: (change_id) ->
  80. change = @getChange(change_id)
  81. return if !change?
  82. @_removeChange(change)
  83. applyOp: (op, metadata = {}) ->
  84. metadata.ts ?= new Date()
  85. # Apply an op that has been applied to the document to our changes to keep them up to date
  86. if op.i?
  87. @applyInsertToChanges(op, metadata)
  88. @applyInsertToComments(op)
  89. else if op.d?
  90. @applyDeleteToChanges(op, metadata)
  91. @applyDeleteToComments(op)
  92. else if op.c?
  93. @addComment(op, metadata)
  94. else
  95. throw new Error("unknown op type")
  96. addComment: (op, metadata) ->
  97. # TODO: Don't allow overlapping comments?
  98. @comments.push comment = {
  99. id: op.t or @newId()
  100. op: # Copy because we'll modify in place
  101. c: op.c
  102. p: op.p
  103. t: op.t
  104. metadata
  105. }
  106. @emit "comment:added", comment
  107. return comment
  108. applyInsertToComments: (op) ->
  109. for comment in @comments
  110. if op.p <= comment.op.p
  111. comment.op.p += op.i.length
  112. @emit "comment:moved", comment
  113. else if op.p < comment.op.p + comment.op.c.length
  114. offset = op.p - comment.op.p
  115. comment.op.c = comment.op.c[0..(offset-1)] + op.i + comment.op.c[offset...]
  116. @emit "comment:moved", comment
  117. applyDeleteToComments: (op) ->
  118. op_start = op.p
  119. op_length = op.d.length
  120. op_end = op.p + op_length
  121. for comment in @comments
  122. comment_start = comment.op.p
  123. comment_end = comment.op.p + comment.op.c.length
  124. comment_length = comment_end - comment_start
  125. if op_end <= comment_start
  126. # delete is fully before comment
  127. comment.op.p -= op_length
  128. @emit "comment:moved", comment
  129. else if op_start >= comment_end
  130. # delete is fully after comment, nothing to do
  131. else
  132. # delete and comment overlap
  133. if op_start <= comment_start
  134. remaining_before = ""
  135. else
  136. remaining_before = comment.op.c.slice(0, op_start - comment_start)
  137. if op_end >= comment_end
  138. remaining_after = ""
  139. else
  140. remaining_after = comment.op.c.slice(op_end - comment_start)
  141. # Check deleted content matches delete op
  142. deleted_comment = comment.op.c.slice(remaining_before.length, comment_length - remaining_after.length)
  143. offset = Math.max(0, comment_start - op_start)
  144. deleted_op_content = op.d.slice(offset).slice(0, deleted_comment.length)
  145. if deleted_comment != deleted_op_content
  146. throw new Error("deleted content does not match comment content")
  147. comment.op.p = Math.min(comment_start, op_start)
  148. comment.op.c = remaining_before + remaining_after
  149. @emit "comment:moved", comment
  150. applyInsertToChanges: (op, metadata) ->
  151. op_start = op.p
  152. op_length = op.i.length
  153. op_end = op.p + op_length
  154. already_merged = false
  155. previous_change = null
  156. moved_changes = []
  157. remove_changes = []
  158. new_changes = []
  159. for change, i in @changes
  160. change_start = change.op.p
  161. if change.op.d?
  162. # Shift any deletes after this along by the length of this insert
  163. if op_start < change_start
  164. change.op.p += op_length
  165. moved_changes.push change
  166. else if op_start == change_start
  167. # If the insert matches the start of the delete, just remove it from the delete instead
  168. if change.op.d.length >= op.i.length and change.op.d.slice(0, op.i.length) == op.i
  169. change.op.d = change.op.d.slice(op.i.length)
  170. change.op.p += op.i.length
  171. if change.op.d == ""
  172. remove_changes.push change
  173. else
  174. moved_changes.push change
  175. already_merged = true
  176. else
  177. change.op.p += op_length
  178. moved_changes.push change
  179. else if change.op.i?
  180. change_end = change_start + change.op.i.length
  181. is_change_overlapping = (op_start >= change_start and op_start <= change_end)
  182. # Only merge inserts if they are from the same user
  183. is_same_user = metadata.user_id == change.metadata.user_id
  184. # If this is an insert op at the end of an existing insert with a delete following, and it cancels out the following
  185. # delete then we shouldn't append it to this insert, but instead only cancel the following delete.
  186. # E.g.
  187. # foo|<--- about to insert 'b' here
  188. # inserted 'foo' --^ ^-- deleted 'bar'
  189. # should become just 'foo' not 'foob' (with the delete marker becoming just 'ar'), .
  190. next_change = @changes[i+1]
  191. is_op_adjacent_to_next_delete = next_change? and next_change.op.d? and op.p == change_end and next_change.op.p == op.p
  192. will_op_cancel_next_delete = is_op_adjacent_to_next_delete and next_change.op.d.slice(0, op.i.length) == op.i
  193. # If there is a delete at the start of the insert, and we're inserting
  194. # at the start, we SHOULDN'T merge since the delete acts as a partition.
  195. # The previous op will be the delete, but it's already been shifted by this insert
  196. #
  197. # I.e.
  198. # Originally: |-- existing insert --|
  199. # | <- existing delete at same offset
  200. #
  201. # Now: |-- existing insert --| <- not shifted yet
  202. # |-- this insert --|| <- existing delete shifted along to end of this op
  203. #
  204. # After: |-- existing insert --|
  205. # |-- this insert --|| <- existing delete
  206. #
  207. # Without the delete, the inserts would be merged.
  208. is_insert_blocked_by_delete = (previous_change? and previous_change.op.d? and previous_change.op.p == op_end)
  209. # If the insert is overlapping another insert, either at the beginning in the middle or touching the end,
  210. # then we merge them into one.
  211. if @track_changes and
  212. is_change_overlapping and
  213. !is_insert_blocked_by_delete and
  214. !already_merged and
  215. !will_op_cancel_next_delete and
  216. is_same_user
  217. offset = op_start - change_start
  218. change.op.i = change.op.i.slice(0, offset) + op.i + change.op.i.slice(offset)
  219. change.metadata.ts = metadata.ts
  220. already_merged = true
  221. moved_changes.push change
  222. else if op_start <= change_start
  223. # If we're fully before the other insert we can just shift the other insert by our length.
  224. # If they are touching, and should have been merged, they will have been above.
  225. # 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
  226. change.op.p += op_length
  227. moved_changes.push change
  228. else if (!is_same_user or !@track_changes) and change_start < op_start < change_end
  229. # This user is inserting inside a change by another user, so we need to split the
  230. # other user's change into one before and after this one.
  231. offset = op_start - change_start
  232. before_content = change.op.i.slice(0, offset)
  233. after_content = change.op.i.slice(offset)
  234. # The existing change can become the 'before' change
  235. change.op.i = before_content
  236. moved_changes.push change
  237. # Create a new op afterwards
  238. after_change = {
  239. op: {
  240. i: after_content
  241. p: change_start + offset + op_length
  242. }
  243. metadata: {}
  244. }
  245. after_change.metadata[key] = value for key, value of change.metadata
  246. new_changes.push after_change
  247. previous_change = change
  248. if @track_changes and !already_merged
  249. @_addOp op, metadata
  250. for {op, metadata} in new_changes
  251. @_addOp op, metadata
  252. for change in remove_changes
  253. @_removeChange change
  254. if moved_changes.length > 0
  255. @emit "changes:moved", moved_changes
  256. applyDeleteToChanges: (op, metadata) ->
  257. op_start = op.p
  258. op_length = op.d.length
  259. op_end = op.p + op_length
  260. remove_changes = []
  261. moved_changes = []
  262. # We might end up modifying our delete op if it merges with existing deletes, or cancels out
  263. # with an existing insert. Since we might do multiple modifications, we record them and do
  264. # all the modifications after looping through the existing changes, so as not to mess up the
  265. # offset indexes as we go.
  266. op_modifications = []
  267. for change in @changes
  268. if change.op.i?
  269. change_start = change.op.p
  270. change_end = change_start + change.op.i.length
  271. if op_end <= change_start
  272. # Shift ops after us back by our length
  273. change.op.p -= op_length
  274. moved_changes.push change
  275. else if op_start >= change_end
  276. # Delete is after insert, nothing to do
  277. else
  278. # When the new delete overlaps an insert, we should remove the part of the insert that
  279. # is now deleted, and also remove the part of the new delete that overlapped. I.e.
  280. # the two cancel out where they overlap.
  281. if op_start >= change_start
  282. # |-- existing insert --|
  283. # insert_remaining_before -> |.....||-- new delete --|
  284. delete_remaining_before = ""
  285. insert_remaining_before = change.op.i.slice(0, op_start - change_start)
  286. else
  287. # delete_remaining_before -> |.....||-- existing insert --|
  288. # |-- new delete --|
  289. delete_remaining_before = op.d.slice(0, change_start - op_start)
  290. insert_remaining_before = ""
  291. if op_end <= change_end
  292. # |-- existing insert --|
  293. # |-- new delete --||.....| <- insert_remaining_after
  294. delete_remaining_after = ""
  295. insert_remaining_after = change.op.i.slice(op_end - change_start)
  296. else
  297. # |-- existing insert --||.....| <- delete_remaining_after
  298. # |-- new delete --|
  299. delete_remaining_after = op.d.slice(change_end - op_start)
  300. insert_remaining_after = ""
  301. insert_remaining = insert_remaining_before + insert_remaining_after
  302. if insert_remaining.length > 0
  303. change.op.i = insert_remaining
  304. change.op.p = Math.min(change_start, op_start)
  305. change.metadata.ts = metadata.ts
  306. moved_changes.push change
  307. else
  308. remove_changes.push change
  309. # We know what we want to preserve of our delete op before (delete_remaining_before) and what we want to preserve
  310. # afterwards (delete_remaining_before). Now we need to turn that into a modification which deletes the
  311. # chunk in the middle not covered by these.
  312. delete_removed_length = op.d.length - delete_remaining_before.length - delete_remaining_after.length
  313. delete_removed_start = delete_remaining_before.length
  314. modification = {
  315. d: op.d.slice(delete_removed_start, delete_removed_start + delete_removed_length)
  316. p: delete_removed_start
  317. }
  318. if modification.d.length > 0
  319. op_modifications.push modification
  320. else if change.op.d?
  321. change_start = change.op.p
  322. if op_end < change_start or (!@track_changes and op_end == change_start)
  323. # Shift ops after us back by our length.
  324. # If we're tracking changes, it must be strictly before, since we'll merge
  325. # below if they are touching. Otherwise, touching is fine.
  326. change.op.p -= op_length
  327. moved_changes.push change
  328. else if op_start <= change_start <= op_end
  329. if @track_changes
  330. # If we overlap a delete, add it in our content, and delete the existing change.
  331. # It's easier to do it this way, rather than modifying the existing delete in case
  332. # we overlap many deletes and we'd need to track that. We have a workaround to
  333. # update the delete in place if possible below.
  334. offset = change_start - op_start
  335. op_modifications.push { i: change.op.d, p: offset }
  336. remove_changes.push change
  337. else
  338. change.op.p = op_start
  339. moved_changes.push change
  340. # Copy rather than modify because we still need to apply it to comments
  341. op = {
  342. p: op.p
  343. d: @_applyOpModifications(op.d, op_modifications)
  344. }
  345. for change in remove_changes
  346. # This is a bit of hack to avoid removing one delete and replacing it with another.
  347. # If we don't do this, it causes the UI to flicker
  348. if op.d.length > 0 and change.op.d? and op.p <= change.op.p <= op.p + op.d.length
  349. change.op.p = op.p
  350. change.op.d = op.d
  351. change.metadata = metadata
  352. moved_changes.push change
  353. op.d = "" # stop it being added
  354. else
  355. @_removeChange change
  356. if @track_changes and op.d.length > 0
  357. @_addOp op, metadata
  358. else
  359. # It's possible that we deleted an insert between two other inserts. I.e.
  360. # If we delete 'user_2 insert' in:
  361. # |-- user_1 insert --||-- user_2 insert --||-- user_1 insert --|
  362. # it becomes:
  363. # |-- user_1 insert --||-- user_1 insert --|
  364. # We need to merge these together again
  365. results = @_scanAndMergeAdjacentUpdates()
  366. moved_changes = moved_changes.concat(results.moved_changes)
  367. for change in results.remove_changes
  368. @_removeChange change
  369. moved_changes = moved_changes.filter (c) -> c != change
  370. if moved_changes.length > 0
  371. @emit "changes:moved", moved_changes
  372. _addOp: (op, metadata) ->
  373. change = {
  374. id: @newId()
  375. op: @_clone(op) # Don't take a reference to the existing op since we'll modify this in place with future changes
  376. metadata: @_clone(metadata)
  377. }
  378. @changes.push change
  379. # Keep ops in order of offset, with deletes before inserts
  380. @changes.sort (c1, c2) ->
  381. result = c1.op.p - c2.op.p
  382. if result != 0
  383. return result
  384. else if c1.op.i? and c2.op.d?
  385. return 1
  386. else
  387. return -1
  388. if op.d?
  389. @emit "delete:added", change
  390. else if op.i?
  391. @emit "insert:added", change
  392. _removeChange: (change) ->
  393. @changes = @changes.filter (c) -> c.id != change.id
  394. if change.op.d?
  395. @emit "delete:removed", change
  396. else if change.op.i?
  397. @emit "insert:removed", change
  398. _applyOpModifications: (content, op_modifications) ->
  399. # Put in descending position order, with deleting first if at the same offset
  400. # (Inserting first would modify the content that the delete will delete)
  401. op_modifications.sort (a, b) ->
  402. result = b.p - a.p
  403. if result != 0
  404. return result
  405. else if a.i? and b.d?
  406. return 1
  407. else
  408. return -1
  409. for modification in op_modifications
  410. if modification.i?
  411. content = content.slice(0, modification.p) + modification.i + content.slice(modification.p)
  412. else if modification.d?
  413. if content.slice(modification.p, modification.p + modification.d.length) != modification.d
  414. throw new Error("deleted content does not match. content: #{JSON.stringify(content)}; modification: #{JSON.stringify(modification)}")
  415. content = content.slice(0, modification.p) + content.slice(modification.p + modification.d.length)
  416. return content
  417. _scanAndMergeAdjacentUpdates: () ->
  418. # This should only need calling when deleting an update between two
  419. # other updates. There's no other way to get two adjacent updates from the
  420. # same user, since they would be merged on insert.
  421. previous_change = null
  422. remove_changes = []
  423. moved_changes = []
  424. for change in @changes
  425. if previous_change?.op.i? and change.op.i?
  426. previous_change_end = previous_change.op.p + previous_change.op.i.length
  427. previous_change_user_id = previous_change.metadata.user_id
  428. change_start = change.op.p
  429. change_user_id = change.metadata.user_id
  430. if previous_change_end == change_start and previous_change_user_id == change_user_id
  431. remove_changes.push change
  432. previous_change.op.i += change.op.i
  433. moved_changes.push previous_change
  434. else if previous_change?.op.d? and change.op.d? and previous_change.op.p == change.op.p
  435. # Merge adjacent deletes
  436. previous_change.op.d += change.op.d
  437. remove_changes.push change
  438. moved_changes.push previous_change
  439. else # Only update to the current change if we haven't removed it.
  440. previous_change = change
  441. return { moved_changes, remove_changes }
  442. _clone: (object) ->
  443. clone = {}
  444. (clone[k] = v for k,v of object)
  445. return clone
  446. if define?
  447. define ["utils/EventEmitter"], load
  448. else
  449. EventEmitter = require("events").EventEmitter
  450. module.exports = load(EventEmitter)