Skip to content

Instantly share code, notes, and snippets.

@tuanalumi
Created October 21, 2021 07:55
Show Gist options
  • Save tuanalumi/950f09168434ac6bc5b092be4c7de20b to your computer and use it in GitHub Desktop.
Save tuanalumi/950f09168434ac6bc5b092be4c7de20b to your computer and use it in GitHub Desktop.
Tracking a specfic type of node changes (deletion, addition) in tiptap/prosemirror
import { Plugin } from 'prosemirror-state'
export default function ({ nodeType, onChange }) {
return new Plugin({
state: {
init: () => null,
// eslint-disable-next-line max-params
apply: (tr, currentValue, oldState, newState) => {
const changes = { added: [], removed: [] }
tr.mapping.maps.forEach(map => {
// eslint-disable-next-line max-params
map.forEach((oldStart, oldEnd, newStart, newEnd) => {
newState.doc.nodesBetween(
newStart,
newEnd,
// eslint-disable-next-line max-params
(node, pos, parent, index) => {
if (node.type.name === nodeType) {
changes.added.push(node)
}
}
)
oldState.doc.nodesBetween(
oldStart,
oldEnd,
// eslint-disable-next-line max-params
(node, pos, parent, index) => {
if (node.type.name === nodeType) {
changes.removed.push(node)
}
}
)
})
// maintain a list of mention with position
})
onChange(changes)
return null
},
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment