overleaf/services/document-updater/app/js/DiffCodec.js

38 lines
871 B
JavaScript
Raw Normal View History

2020-12-07 15:29:24 -05:00
const { diff_match_patch: DMP } = require('../lib/diff_match_patch')
const dmp = new DMP()
2014-02-12 05:40:42 -05:00
2020-12-07 15:27:41 -05:00
module.exports = {
ADDED: 1,
REMOVED: -1,
UNCHANGED: 0,
2014-02-12 05:40:42 -05:00
diffAsShareJsOp(before, after, callback) {
const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
dmp.diff_cleanupSemantic(diffs)
2014-02-12 05:40:42 -05:00
const ops = []
let position = 0
2020-12-07 15:25:20 -05:00
for (const diff of diffs) {
const type = diff[0]
const content = diff[1]
if (type === this.ADDED) {
ops.push({
i: content,
p: position
})
position += content.length
} else if (type === this.REMOVED) {
ops.push({
d: content,
p: position
})
} else if (type === this.UNCHANGED) {
position += content.length
} else {
2020-12-07 15:28:25 -05:00
throw new Error('Unknown type')
}
}
2020-12-07 15:25:52 -05:00
callback(null, ops)
}
}