2020-12-07 16:13:36 -05:00
|
|
|
const DMP = require('diff-match-patch')
|
2020-12-07 15:29:24 -05:00
|
|
|
const dmp = new DMP()
|
2014-02-12 05:40:42 -05:00
|
|
|
|
2021-01-14 15:11:15 -05:00
|
|
|
// Do not attempt to produce a diff for more than 100ms
|
|
|
|
dmp.Diff_Timeout = 0.1
|
|
|
|
|
2020-12-07 15:27:41 -05:00
|
|
|
module.exports = {
|
2020-05-06 06:09:33 -04:00
|
|
|
ADDED: 1,
|
|
|
|
REMOVED: -1,
|
|
|
|
UNCHANGED: 0,
|
2014-02-12 05:40:42 -05:00
|
|
|
|
2024-04-02 09:49:33 -04:00
|
|
|
diffAsShareJsOp(before, after) {
|
2020-05-06 06:09:33 -04:00
|
|
|
const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
|
|
|
|
dmp.diff_cleanupSemantic(diffs)
|
2014-02-12 05:40:42 -05:00
|
|
|
|
2020-05-06 06:09:33 -04:00
|
|
|
const ops = []
|
|
|
|
let position = 0
|
2020-12-07 15:25:20 -05:00
|
|
|
for (const diff of diffs) {
|
2020-05-06 06:09:33 -04:00
|
|
|
const type = diff[0]
|
|
|
|
const content = diff[1]
|
|
|
|
if (type === this.ADDED) {
|
|
|
|
ops.push({
|
|
|
|
i: content,
|
2021-07-13 07:04:42 -04:00
|
|
|
p: position,
|
2020-05-06 06:09:33 -04:00
|
|
|
})
|
|
|
|
position += content.length
|
|
|
|
} else if (type === this.REMOVED) {
|
|
|
|
ops.push({
|
|
|
|
d: content,
|
2021-07-13 07:04:42 -04:00
|
|
|
p: position,
|
2020-05-06 06:09:33 -04:00
|
|
|
})
|
|
|
|
} else if (type === this.UNCHANGED) {
|
|
|
|
position += content.length
|
|
|
|
} else {
|
2020-12-07 15:28:25 -05:00
|
|
|
throw new Error('Unknown type')
|
2020-05-06 06:09:33 -04:00
|
|
|
}
|
|
|
|
}
|
2024-04-02 09:49:33 -04:00
|
|
|
return ops
|
2021-07-13 07:04:42 -04:00
|
|
|
},
|
2020-05-06 06:09:33 -04:00
|
|
|
}
|