DiffCodec.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* eslint-disable
  2. camelcase,
  3. handle-callback-err,
  4. new-cap,
  5. no-throw-literal,
  6. no-unused-vars,
  7. */
  8. // TODO: This file was created by bulk-decaffeinate.
  9. // Fix any style issues and re-enable lint.
  10. /*
  11. * decaffeinate suggestions:
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let DiffCodec
  16. const { diff_match_patch } = require('../lib/diff_match_patch')
  17. const dmp = new diff_match_patch()
  18. module.exports = DiffCodec = {
  19. ADDED: 1,
  20. REMOVED: -1,
  21. UNCHANGED: 0,
  22. diffAsShareJsOp(before, after, callback) {
  23. if (callback == null) {
  24. callback = function (error, ops) {}
  25. }
  26. const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
  27. dmp.diff_cleanupSemantic(diffs)
  28. const ops = []
  29. let position = 0
  30. for (const diff of diffs) {
  31. const type = diff[0]
  32. const content = diff[1]
  33. if (type === this.ADDED) {
  34. ops.push({
  35. i: content,
  36. p: position
  37. })
  38. position += content.length
  39. } else if (type === this.REMOVED) {
  40. ops.push({
  41. d: content,
  42. p: position
  43. })
  44. } else if (type === this.UNCHANGED) {
  45. position += content.length
  46. } else {
  47. throw 'Unknown type'
  48. }
  49. }
  50. callback(null, ops)
  51. }
  52. }