DiffCodec.js 925 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const DMP = require('diff-match-patch')
  2. const dmp = new DMP()
  3. // Do not attempt to produce a diff for more than 100ms
  4. dmp.Diff_Timeout = 0.1
  5. module.exports = {
  6. ADDED: 1,
  7. REMOVED: -1,
  8. UNCHANGED: 0,
  9. diffAsShareJsOp(before, after, callback) {
  10. const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
  11. dmp.diff_cleanupSemantic(diffs)
  12. const ops = []
  13. let position = 0
  14. for (const diff of diffs) {
  15. const type = diff[0]
  16. const content = diff[1]
  17. if (type === this.ADDED) {
  18. ops.push({
  19. i: content,
  20. p: position,
  21. })
  22. position += content.length
  23. } else if (type === this.REMOVED) {
  24. ops.push({
  25. d: content,
  26. p: position,
  27. })
  28. } else if (type === this.UNCHANGED) {
  29. position += content.length
  30. } else {
  31. throw new Error('Unknown type')
  32. }
  33. }
  34. callback(null, ops)
  35. },
  36. }