How to set custom class to a prosemirror plugin on focused state only ?
I am using tiptap.dev for creating a custom Mark extension. Now I need to have a class in my custom extension only when it is focused. How to achieve this?
Code:
import { Mark, mergeAttributes } from '@tiptap/core'
import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from '@tiptap/pm/state'
import { Decoration, DecorationSet } from '@tiptap/pm/view'
export const Suggestion = Mark.create({
name: 'suggestion',
addOptions() {
return {
HTMLAttributes: {
class: 'suggestion-highlight',
},
}
},
parseHTML() {
return [
{
tag: 'span[data-type="suggestion"]',
},
]
},
renderHTML({ HTMLAttributes }) {
return [
'span',
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0,
]
},
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey('activeSuggestion'),
props: {
decorations: (state) => {
console.log('state', state)
}
}
})
]
}
})
I have tried this which kind of works but creates a nested span
which I don’t really want.
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey('activeSuggestion'),
props: {
decorations(state) {
const selection = state.selection;
const decorations = [];
state.doc.nodesBetween(selection.from, selection.to, (node, position) => {
const isSuggestionNode = node.marks.some(mark => mark.type.name === 'suggestion');
if (isSuggestionNode) {
decorations.push(Decoration.inline(position, position + node.nodeSize, { class: 'suggestion-active' }));
console.log(position, position + node.nodeSize)
console.log(node)
}
});
return DecorationSet.create(state.doc, decorations);
}
}
})
]
}
When not focused:
<span class="suggestion-highlight">Hello</span>
When focused:
<span class="suggestion-highlight"><span class="suggestion-active">Hello</span></span>