DiffCodec.js 842 B

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