Skip to content

Instantly share code, notes, and snippets.

@marijnh
Created August 17, 2016 14:11
Show Gist options
  • Save marijnh/2b15b3bfb6c2565d5d39c73f6e92c5ef to your computer and use it in GitHub Desktop.
Save marijnh/2b15b3bfb6c2565d5d39c73f6e92c5ef to your computer and use it in GitHub Desktop.
Compute changed range from ProseMirror steps
function changedRanges(history, group) {
let ranges = []
history.forEach((step, i) => {
let map = step.posMap()
ranges = ranges.map(range => {
let from = map.map(range.from, 1), to = Math.max(from, map.map(range.to, -1))
return {from, to}
})
if (group.indexOf(i) > -1) {
let newRanges = []
map.forEach((_f, _t, from, to) => newRanges.push({from, to}))
ranges = joinRanges(ranges, newRanges)
}
})
return ranges
}
function joinRanges(a, b) {
let ranges = a.slice(), i = 0
b.forEach(({from, to}) => {
while (i < ranges.length && ranges[i].to < from) i++
let end = i
while (end < ranges.length && ranges[end].from <= to) {
from = Math.min(ranges[end].from, from)
to = Math.max(ranges[end].to, to)
end++
}
ranges.splice(i, end - i, {from, to})
})
return ranges
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment