Replies: 3 comments 5 replies
-
@Saul-Mirone any pointers here? I've spent way too many hours on this 😓 This feels like something that should be relatively simple, but I need some directions. I've tried replicating logic in a few other plugins, but their requirements are quite different, since my use case does not depend on any markup, but rather presence of text. |
Beta Was this translation helpful? Give feedback.
-
Do you mean a highlight you can turn on or off (like making text bold), or something else? |
Beta Was this translation helpful? Give feedback.
-
An absolutely terrible example as a proof of concept. It adds In the real world, you would probably need to use something like prosemirrors 'descendants' to find actual positions of words, inspiration maybe in https://github.com/mattberkowitz/prosemirror-find-replace or highlighter plugins. import { Plugin, PluginKey } from "@milkdown/prose/state";
import { $prose } from "@milkdown/utils";
import { Decoration, DecorationSet } from "@milkdown/prose/view";
const highlightKey = new PluginKey("MilkdownHighlights")
export const highlightPlugin = $prose((ctx) => {
return new Plugin({
key: highlightKey,
props: {
decorations(state) {
return highlightKey.getState(state).decorations;
}
},
state: {
init() {
return {
decorations: DecorationSet.empty,
};
},
apply(tr, value, prevState, state) {
// The array of all active decorations
const highlights = [];
// List of words to look for
const lookFor = [
{
text: 'similique',
id: '123ABC',
}, {
text: 'tellus',
id: '345DEF',
}];
//
state.doc.nodesBetween(null, state.doc.nodeSize - 2, (node, path) => {
lookFor.forEach((keyword) => {
[...node.textContent.matchAll(keyword.text)].forEach((match) => {
highlights.push(Decoration.inline(path + match.index + 1, path + match.index + match[0].length, {
nodeName: 'mark',
'data-id': keyword.id,
}));
});
});
});
// Nothing to highlight
if (!highlights.length) return {
decorations: DecorationSet.empty,
};
// Highlight it all!
return {
decorations: DecorationSet.create(state.doc, highlights),
};
}
}
})
}); Edit: using nodesBetween instead of raw markdown. |
Beta Was this translation helpful? Give feedback.
-
I need to highlight a specific keyword in a document. Where do I start? Just looking for high level guidance.
Beta Was this translation helpful? Give feedback.
All reactions