Merge pull request #607 from BrianHung/HighlightTransaction

Apply decorations in HighlightPlugin if change in named nodes.
This commit is contained in:
Philipp Kühn 2020-04-01 20:32:19 +02:00 committed by GitHub
commit 5574ac4d56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -62,17 +62,20 @@ export default function HighlightPlugin({ name }) {
name: new PluginKey('highlight'), name: new PluginKey('highlight'),
state: { state: {
init: (_, { doc }) => getDecorations({ doc, name }), init: (_, { doc }) => getDecorations({ doc, name }),
apply: (transaction, decorationSet, oldState, state) => { apply: (transaction, decorationSet, oldState, newState) => {
// TODO: find way to cache decorations // TODO: find way to cache decorations
// see: https://discuss.prosemirror.net/t/how-to-update-multiple-inline-decorations-on-node-change/1493 // https://discuss.prosemirror.net/t/how-to-update-multiple-inline-decorations-on-node-change/1493
const oldNodeName = oldState.selection.$head.parent.type.name
const nodeName = state.selection.$head.parent.type.name const newNodeName = newState.selection.$head.parent.type.name
const previousNodeName = oldState.selection.$head.parent.type.name const oldNodes = findBlockNodes(oldState.doc)
.filter(item => item.node.type.name === name)
if (transaction.docChanged && [nodeName, previousNodeName].includes(name)) { const newNodes = findBlockNodes(newState.doc)
.filter(item => item.node.type.name === name)
// Apply decorations if selection includes named node, or transaction changes named node.
if (transaction.docChanged && ([oldNodeName, newNodeName].includes(name)
|| newNodes.length !== oldNodes.length)) {
return getDecorations({ doc: transaction.doc, name }) return getDecorations({ doc: transaction.doc, name })
} }
return decorationSet.map(transaction.mapping, transaction.doc) return decorationSet.map(transaction.mapping, transaction.doc)
}, },
}, },