overleaf/services/document-updater/app/js/DiffCodec.js
Eric Mc Sween de247302b1 Use a centralized diff-match-patch package
We use our own fork of the diff-match-patch npm package, which adds an
optimization for the semantic alignment loop.
2020-12-07 16:15:19 -05:00

37 lines
842 B
JavaScript

const DMP = require('diff-match-patch')
const dmp = new DMP()
module.exports = {
ADDED: 1,
REMOVED: -1,
UNCHANGED: 0,
diffAsShareJsOp(before, after, callback) {
const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
dmp.diff_cleanupSemantic(diffs)
const ops = []
let position = 0
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 {
throw new Error('Unknown type')
}
}
callback(null, ops)
}
}